这是后续这个问题 https://stackoverflow.com/questions/1398796/casting-with-reflection关于通过反射转换值。将某种类型的对象转换为另一种类型可以这样完成:
object convertedValue = Convert.ChangeType(value, targetType);
给定两个 Type 实例(比如 FromType 和 ToType),有没有办法测试转换是否会成功?
例如。我可以写一个这样的扩展方法吗:
public static class TypeExtensions
{
public static bool CanChangeType(this Type fromType, Type toType)
{
// what to put here?
}
}
编辑:这就是我现在所拥有的。丑陋,但我还没有看到其他方法......
bool CanChangeType(Type sourceType, Type targetType)
{
try
{
var instanceOfSourceType = Activator.CreateInstance(sourceType);
Convert.ChangeType(instanceOfSourceType, targetType);
return true; // OK, it can be converted
}
catch (Exception ex)
{
return false;
}
我刚刚遇到了同样的问题,我使用 Reflector 来查看 ChangeType 的源代码。 ChangeType 在 3 种情况下抛出异常:
- 转换类型为空
- 值为空
- 值未实现 IConvertible
检查完这三项后,就保证可以转换了。因此,您只需亲自检查这三件事即可节省大量性能并删除 try{}/catch{} 块:
public static bool CanChangeType(object value, Type conversionType)
{
if (conversionType == null)
{
return false;
}
if (value == null)
{
return false;
}
IConvertible convertible = value as IConvertible;
if (convertible == null)
{
return false;
}
return true;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)