gpt4 book ai didi

c# - 测试 Convert.ChangeType 是否可以在两种类型之间工作

转载 作者:IT王子 更新时间:2023-10-29 04:16:33 25 4
gpt4 key购买 nike

这是 this question 的后续行动关于用反射转换值。将某种类型的对象转换为另一种类型可以像这样完成:

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 种情况下抛出异常:

  1. 转化类型为空
  2. 值为空
  3. 值没有实现 IConvertible

这3个勾选后,保证可以转换。因此,您可以通过简单地自己检查这三件事来节省大量性能并删除 try{}/catch{} block :

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;
}

关于c# - 测试 Convert.ChangeType 是否可以在两种类型之间工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1399273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com