Set property Nullable<> by reflection

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

    I hit this same problem as well as an issue with Convert.ChangeType not handling DateTimes on Nullables so I combined a couple of stackoverflow solutions with some .NET 4 dynamic magic to get something I think is kind of sweet. If you look at the code, we use dynamic to type the object to Nullable at run time, then the run time treats it differently and allows assignments of the base type to the nullable object.

    public void GenericMapField(object targetObj, string fieldName, object fieldValue)
    {
        PropertyInfo prop = targetObj.GetType().GetProperty(fieldName);
        if (prop != null)
        {
            if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                dynamic objValue = System.Activator.CreateInstance(prop.PropertyType);
                objValue = fieldValue;
                prop.SetValue(targetObj, (object)objValue, null);
            }
            else
            {
                prop.SetValue(targetObj, fieldValue, null);
            }
        }
    }
    

提交回复
热议问题