如何使用反射转换类型

How to Convert Types Using Reflection

请考虑此代码:

string propertyValue = "1";
PropertyInfo info = obj.GetType().GetProperty("MyProperty");
info.SetValue(detail, Convert.ChangeType(propertyValue, info.PropertyType), null);

问题是 info.PropertyType 的类型是 System.Byte?,当要执行第 3 行时,我得到了这个错误:

"Invalid cast from 'System.String' to 'System.Nullable`1[[System.Byte, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'."}

我如何解决这个问题?

谢谢

Convert.ChangeType() 存在可空类型问题。 首先尝试检查类型是否可为空。如果是,取底层类型:

var targetType = Nullable.GetUnderlyingType(info.PropertyType);
if (targetType == null)
    targetType = info.PropertyType;

您可以致电 Convert.ChangeType(propertyValue, targetType)

不幸的是,这会给您带来另一个问题:ChangeType() 不会将 "1""0" 转换为布尔值。但是它适用于 "true""false"。它也适用于 01 作为整数。

Check the fiddle I prepared for you

这个问题对你来说可能是个问题,也可能不是——我不知道这些值来自哪个规范。

这个解决方案更好:

PropertyInfo info = detail.GetType().GetProperty(propertyName);

var targetType = Nullable.GetUnderlyingType(info.PropertyType);
if (targetType == null)
    targetType = info.PropertyType;

object safeValue = (propertyValue == null) ? null : Convert.ChangeType(propertyValue, targetType);

info.SetValue(detail, safeValue, null);