Set property Nullable<> by reflection

前端 未结 6 882
暖寄归人
暖寄归人 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条回答
  •  梦毁少年i
    2021-01-11 14:08

    public static void SetValue(object target, string propertyName, object value)
    {
      if (target == null)
        return;
    
      PropertyInfo propertyInfo = target.GetType().GetProperty(propertyName);
    
      object convertedValue = value;
      if (value != null && value.GetType() != propertyInfo.PropertyType)
      {
        Type propertyType = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
        convertedValue = Convert.ChangeType(value, propertyType);
      }
    
      propertyInfo.SetValue(target, convertedValue, null);
    }
    

提交回复
热议问题