简体   繁体   中英

c# Reflection of a nested struct property

I'm trying to do some dynamic text to object parsing, however, I have run into a snag when creating and setting nested property values for structs.

If I have a property in an object that is a struct, whenever I use reflection to obtain the struct object and set any of it's properties/fields, the value on the object is not changed. Take the object graph below.

public struct MyStruct
{
    public int MyIntProp {get;set;}
}

public class MyObj
{
    public MyStruct NestedStruct {get;set;}
}

PropertyInfo pInfo = (myObj.GetType()).GetProperty("NestedStruct");
object nestedStruct = pInfo.GetValue(myObj); // This is the nested struct however it is only a copy not the actual object
PropertyInfo intInfo = (pInfo.PropertyType).GetProperty("MyIntProp");
intInfo.SetValue(nestedStruct, 23); // this sets the MyIntProp on the nestedStruct, but it is not set on the myObj.NestedStruct.  My goal is to set object on that NestedStruct via reflection.

When I use reflection to obtain the NestedStruct property and then set the MyIntProp on that struct, the original MyObj.NestedStruct.MyIntProp doesn't change. Naturally I attribute this to the fact that the struct is a value type and not a reference type.

So the real question is how I can use reflection to obtain the reference to a value type.

If I have a property in an object that is a struct, whenever I use reflection to obtain the struct object and set any of it's properties/fields, the value on the object is not changed.

Well, no - because on this line:

object nestedStruct = pInfo.GetValue(myObj);

... you're copying the value, as it's a value type. You're also boxing it - which is fine, because it means when you mutate it in the intInfo.SetValue call, it's the boxed copy which is modified. (If you were boxing it at the point of calling intInfo.SetValue , that would really be hopeless.)

After you've made the change within the boxed copy, you then need to set it back into the property of the object:

pInfo.SetValue(myObject, nestedStruct);

It would be instructive to try doing what you're doing not using reflection:

MyObj myObj = new MyObj();
myObj.NestedStruct.MyIntProp = 23;

The compiler will give you an error on the last line, explaining that it's a silly thing to do:

Test.cs(20,9): error CS1612: Cannot modify the return value of 'MyObj.NestedStruct' because it is not a variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM