Set property Nullable<> by reflection

前端 未结 6 901
暖寄归人
暖寄归人 2021-01-11 13:35

I try to set a Nullable<> property dynamicly.

I Get my property ex :

PropertyInfo property = class.GetProperty(\"PropertyName\"); // My property i         


        
6条回答
  •  盖世英雄少女心
    2021-01-11 14:15

    If it's a nullable int, you'll need to use an int parameter, not a string.

     property.SetValue(klass,1256,null);
    

    Note the change to klass, instead of class, as class is a reserved keyword. You could also use @class if absolutely necessary (quoting it).

    If your property is a generic, then I think you'll probably need to use Convert to convert whatever you have to whatever you need.

     var nullType = Nullable.GetUnderlyingType(property.PropertyType)
     var value = Convert.ChangeType("1256", nullType );
     property.SetValue(klass, value, null );
    

提交回复
热议问题