how to set nullable type via reflection code ( c#)?

后端 未结 8 1336
我寻月下人不归
我寻月下人不归 2020-12-28 16:05

I need to set the properties of a class using reflection.

I have a Dictionary with property names and string values.

Inside

相关标签:
8条回答
  • 2020-12-28 16:43
    1. One way to do this is:

      type.GetGenericTypeDefinition() == typeof(Nullable<>)
      
    2. Just set is as per any other reflection code:

      propertyInfo.SetValue(yourObject, yourValue);
      
    0 讨论(0)
  • 2020-12-28 16:44

    Why do you need to know if it is nullable? And do you mean "reference-type", or "Nullable<T>"?

    Either way, with string values, the easiest option would be via the TypeConverter, which is more-easily (and more accurately) available on PropertyDescriptor:

    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
    // then per property...
    PropertyDescriptor prop = props[propName];
    prop.SetValue(obj, prop.Converter.ConvertFromInvariantString(value));
    

    This should use the correct converter, even if set per-property (rather than per-type). Finally, if you are doing lots of this, this allows for acceleration via HyperDescriptor, without changing the code (other than to enable it for the type, done once only).

    0 讨论(0)
提交回复
热议问题