问题描述
这是关于使用反射转换值的这个问题的后续.可以像这样将某种类型的对象转换为另一种类型:
This is a follow-up to this question about converting values with reflection. Converting an object of a certain type to another type can be done like this:
object convertedValue = Convert.ChangeType(value, targetType);
给定两个 Type 实例(比如 FromType 和 ToType),有没有办法测试转换是否成功?
Given two Type instances (say FromType and ToType), is there a way to test whether the conversion will succeed?
例如我可以编写这样的扩展方法吗:
E.g. can I write an extension method like this:
public static class TypeExtensions
{
public static bool CanChangeType(this Type fromType, Type toType)
{
// what to put here?
}
}
这就是我现在所拥有的.丑,但我还没有看到另一种方式......
This is what I have right now. Ugly, but I don't see another way yet...
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 种情况下抛出异常:
I was just encountering this same issue, and I used Reflector to look at the source for ChangeType. ChangeType throws exceptions in 3 cases:
- conversionType 为空
- 值为空
- 值未实现 IConvertible
这3个都勾选后,就保证可以转换了.因此,您只需自己检查这 3 件事,即可节省大量性能并移除 try{}/catch{} 块:
After those 3 are checked, it is guaranteed that it can be converted. So you can save a lot of performance and remove the try{}/catch{} block by simply checking those 3 things yourself:
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;
}
这篇关于测试 Convert.ChangeType 是否适用于两种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!