PropertyInfo SetValue and nulls

前端 未结 2 562
Happy的楠姐
Happy的楠姐 2021-02-14 09:35

If I have something like:

object value = null;
Foo foo = new Foo();

PropertyInfo property = Foo.GetProperties().Single(p => p.Name == \"IntProperty\");
prope         


        
2条回答
  •  粉色の甜心
    2021-02-14 09:50

    You can use PropertyInfo.PropertyType.IsAssignableFrom(value.GetType()) expression to determine whether specified value can be written into property. But you need to handle case when value is null, so in this case you can assign it to property only if property type is nullable or property type is reference type:

    public bool CanAssignValueToProperty(PropertyInfo propertyInfo, object value)
    {
        if (value == null)
            return Nullable.GetUnderlyingType(propertyInfo.PropertyType) != null ||
                   !propertyInfo.IsValueType;
        else
            return propertyInfo.PropertyType.IsAssignableFrom(value.GetType());
    }
    

    Also, you may find useful Convert.ChangeType method to write convertible values to property.

提交回复
热议问题