Aiko West
Aiko West

Reputation: 791

Reflection: How to get the class object via PropertyInfo

I have 2 classes. ClassA has some objects of ClassB called Field01, Field02, ... Class A also has a list of ClassB items.

I know the name of the ClassB items and want to fill the ClassB items with the values from the list.

Example code:

public class ClassA
{
    public ClassB Field01 {get;set;}
    public ClassB Field02 {get;set;}
    //...

    List<ClassB> myItems;

    public void FillItems()
    {
        foreach(var item in MyItems)
        {
           // what I want in hardcode:
           Field01.ValueA = MyItems[0].ValueA;
           Field01.ValueB = MyItems[0].ValueB;
           Field02.ValueA = MyItems[1].ValueA;
           // ...
        }
    }
}

public class ClassB 
{
    public string ValueA {get;set;}
    public string ValueB {get;set;}
}

In my case I'll have a counting variable which will create the Field01, Field02, Field03, ... names depending on how many items are in my List (there are always enough ClassB fields in ClassA to fill)

I know i can get the PropertyInfo of my ClassB items via name, but I don't know you I can access the ClassB attributes ValueA and ValueB

// If ClassB was just a string or object this would work
Type myType = typeof(ClassA);
PropertyInfo myPropInfo = myType.GetProperty("Field01");
myPropInfo.SetValue(this, "Hello", null);

Upvotes: 0

Views: 1331

Answers (1)

Sweeper
Sweeper

Reputation: 273968

Since you know the declaring type of the properties is ClassB, you can get the PropertyInfo of ValueA and ValueB. Then, you need to get the value of FieldXX (not set it!) and set ValueA and ValueB.

We are going to be dealing with multiple Type, PropertyInfo and object objects, so you should name your variables appropriately, instead of just myPropInfo or myType.

for (int i = 0 ; i < MyItems.Count ; i++) {
    var classAType = typeof(ClassA);
    var classBType = typeof(ClassB);
    var fieldInfo = classAType.GetProperty("Field" + $"{i}".PadLeft(2, '0'));
    var fieldValue = fieldInfo.GetValue(this);
    var valueAInfo = classBType.GetProperty(nameof(ClassB.ValueA));
    var valueBInfo = classBType.GetProperty(nameof(ClassB.ValueB));
    valueAInfo.SetValue(fieldValue, valueAInfo.GetValue(MyItems[i]));
    valueBInfo.SetValue(fieldValue, valueBInfo.GetValue(MyItems[i]));
}

Upvotes: 1

Related Questions