C #: dynamically convert a primitive to Nullable <>

I use reflection to iterate over the properties of objects. For Nullable<> types, the type is returned correctly using the PropertyType . However, when I call the getter property (either through PropertyType.GetGetMethod().Invoke(obj, new object[0]) or PropertyType.GetValue(obj, null) ), the result type is an expanded primitive, not Nullable<> . For the reason, I would prefer not to deal with it, I need to convert this result to its Nullable<> . In such cases, an InvalidCastException :

 Convert.ChangeType(property.GetValue(obj, null), property.PropertyType); 

Is there any other way to ensure that the type of the property value always matches the type of the property?

+4
source share
1 answer

You cannot do this in the reflection code, because in the reflection code you are talking about object , and there is n’t such a thing as in the Nullable<T> box - this is either the base value in the box, or null .

If you know the actual type, you can use the constructor to create the wrapped value, but should only be assigned to the entered field / variable Nullable<T> - not object - otherwise the CLI will open it again.

However, for the same reason you do not need it ; it terminates when using reflection; any code, such as SetValue , will take an object and do what it needs to; regardless of whether it is null or the base value in the box, it will be processed correctly.

Basically, the CLI has special handling when boxing and unpacking Nullable<T> , which makes the question invalid.

+5
source

Source: https://habr.com/ru/post/1386090/


All Articles