C# reflection : How to set nested Property of nest

2019-08-04 01:40发布

Imagine following "path" :

MyObject.MyFirstList[0].MySecondList[0].MyProperty = "Hello"

MyProperty is of type String. None of the types is known at compiletime, only runtime via reflection of assembly.

I have everything, but i can not set the second list on the first with SetValue. I always get either null-ref exceptions or "target type does not match".

What I have tried so far:

iteration 1:

var constructedList = Activator.CreateInstance(constructedListType);
target.GetType().GetProperty(propertyToAdd).SetValue(target, constructedList)

Iteration 2:

Same way, works as well. So now we have MyObject.MyFirstList[0].MySecondList[]

Iteration 3: TODO: Create instance of first object of MySecondList and set its MyProperty-property to the created property:

var target = Activator.CreateInstance(typeOfItem);
target.GetType().GetProperty(propertyToAdd)?.SetValue(target, null);

So to summarize the question:

This works:

someInstance.GetType().GetProperty(someProperty).SetValue(someInstance, objToSet);

Why does something like this not work? Or does it - if yes, how?

someInstance.GetType().GetProperty(someList.listInsideSomeList.finalProperty).SetValue(...);

1条回答
萌系小妹纸
2楼-- · 2019-08-04 01:58

In short, reflection provides you with means to get information on a type. It cannot be used to reference the property of another type (as shown in your last example).

You are on the right track, but you need to go from right to left in your path. So taken you have some nested properties. You first create the nested object, such as:

var objNested = Activator.CreateInstance(objNestedType);
objNestedType.GetProperty(nestedPropertyName).SetValue(objNested, value);

and then you add your newly created object to its 'parent':

var objBase = Activator.CreateInstance(objBaseType);
objBaseType.GetProperty(basePropertyName).SetValue(objBase, objNested);

Arrays are bit different. Reflection expects you to write down the final value when using propertyinfo.SetValue, in case of an array this is the entire array value. In order to do this you can use Array.CreateInstance(typeof(arrayType), arrayLength) to create a new array and use the 'SetValue(object, index)' method to set its contents.

查看更多
登录 后发表回答