Set property Nullable<> by reflection

前端 未结 6 840
暖寄归人
暖寄归人 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:12

    If you want to convert an arbitrary string to the underlying type of the Nullable, you can use the Convert class:

    var propertyInfo = typeof(Foo).GetProperty("Bar");
    object convertedValue = null;
    try 
    { 
        convertedValue = System.Convert.ChangeType("1256", 
            Nullable.GetUnderlyingType(propertyInfo.PropertyType));
    } 
    catch (InvalidCastException)
    {
        // the input string could not be converted to the target type - abort
        return;
    }
    propertyInfo.SetValue(fooInstance, convertedValue, null);
    

    This example will work if the target type is int, short, long (or unsigned variants, since the input string represents a non-negative number), double, float, or decimal. Caveat: this is not fast code.

提交回复
热议问题