相关疑难解决方法(0)

测试Convert.ChangeType是否适用于两种类型

这是关于使用反射转换值的问题的后续行动.将某种类型的对象转换为另一种类型可以这样做:

object convertedValue = Convert.ChangeType(value, targetType);
Run Code Online (Sandbox Code Playgroud)

给定两个Type实例(比如FromType和ToType),有没有办法测试转换是否成功?

我可以写一个像这样的扩展方法:

public static class TypeExtensions
{
    public static bool CanChangeType(this Type fromType, Type toType)
    {
        // what to put here?
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:这就是我现在所拥有的.丑陋,但我还没有看到另一种方式......

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;
  }
Run Code Online (Sandbox Code Playgroud)

c# reflection

27
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×1

reflection ×1