Reflection and update property of in heritaed class RRS feed

  • Question

  • i have a class B that inherits class A :

    public class A { public int x; public int y; } public class B : A { public int y; }

    public class g {

      public string name;

    public B b;


    i want to update the fields : 

    //i fetch data from db 

    PropertyInfo[] properties = typeof(ExtraFields).GetProperties();
                            foreach (PropertyInfo property in properties)
                                var extraData = new B();
                                var class1Type = typeof(B);
                                    class1Type.GetProperty(property.Name, BindingFlags.FlattenHierarchy |
                                                                          BindingFlags.Instance |
                                                                          BindingFlags.Public).SetValue(g.b, row[property.Name]);
                                catch (Exception ex)
                                    int xxx = 1;

    i am trying to update the fields of class A.

    i get an error :

    {"Column 'x' does not belong to table Table."}

    1. what is wrong with the code?

    2. how can i annotate some properties so they will eb skipped in this process?

    Tuesday, October 20, 2020 7:01 AM


  • Hi  want 2 Learn,
    In your code,   "public int x" ans "public int y;" are fields not properties.
    So you need to use GetField() method instead of GetProperty().
    And when you use SetValue (object obj, object value) method, you need to note the parameters
    obj Object
    The object whose field value will be set, you need to change your  "g.b" to "B" or "A". 
    value Object
    The value to assign to the field.
    Here are some related links you can refer to.
    [Set value of private field]
    [What is the difference between a field and a property?]
    Best Regards,
    Daniel Zhang

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, October 21, 2020 3:20 AM