测试是否Convert.ChangeType将两种类型的工作 [英] Test if Convert.ChangeType will work between two types

查看:311
本文介绍了测试是否Convert.ChangeType将两种类型的工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个后续这个问题了解与反思转换值。转换某种类型的对象为另一种类型可以这样做:

 对象convertedValue = Convert.ChangeType(价值,TARGETTYPE ); 



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



例如。我可以写一个扩展方法是这样的:

 公共静态类TypeExtensions 
{
公共静态布尔CanChangeType (这种类型fromType,类型toType)
{
//放什么在这里?
}
}



编辑:这是我现在所拥有的。难看,但我没有看到另一种方式尚未...

 布尔CanChangeType(类型sourceType的,类型TARGETTYPE)
{

{
VAR instanceOfSourceType = Activator.CreateInstance(sourceType的);
Convert.ChangeType(instanceOfSourceType,TARGETTYPE);
返回真; // OK,就可以转换
}
赶上(异常前)
{
返回FALSE;
}


解决方案

我只是遇到同样的的问题,我用反射来看看源的changetype。一changeType抛出异常3例:

  1。 conversionType为空。 
2.值为null。
3的值不实现IConvertible

在这些3被检查,可以保​​证它可以转换。所以,你可以节省大量的性能和简单地检查那些三件事情自己删除尝试{} / catch语句{}块:

 公共静态布尔CanChangeType(对象的值,类型conversionType)
{
如果(conversionType == NULL)
{
返回false;
}

如果(价值== NULL)
{
返回false;
}

IConvertible转换=值IConvertible;

如果(敞篷== NULL)
{
返回false;
}

返回真;
}


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

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

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

解决方案

I was just encountering this same issue, and I used Reflector to look at the source for ChangeType. ChangeType throws exceptions in 3 cases:

1. conversionType is null.
2. value is null.
3. value does not implement IConvertible

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将两种类型的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆