Cast a property to its actual type dynamically using reflection

后端 未结 7 983
梦毁少年i
梦毁少年i 2020-12-09 08:29

I need to cast a property to its actual type dynamically. How do I/Can I do this using reflection?

To explain the real scenario that I am working on a bit. I am tryi

7条回答
  •  一整个雨季
    2020-12-09 08:59

    public object CastPropertyValue(PropertyInfo property, string value) { 
    if (property == null || String.IsNullOrEmpty(value))
        return null;
    if (property.PropertyType.IsEnum)
    {
        Type enumType = property.PropertyType;
        if (Enum.IsDefined(enumType, value))
            return Enum.Parse(enumType, value);
    }
    if (property.PropertyType == typeof(bool))
        return value == "1" || value == "true" || value == "on" || value == "checked";
    else if (property.PropertyType == typeof(Uri))
        return new Uri(Convert.ToString(value));
    else
        return Convert.ChangeType(value, property.PropertyType);  }
    

提交回复
热议问题