简体   繁体   English

使用反射在运行时转换类型?

[英]Converting Types in runtime using reflection?

Please take a look at the following code: 请看下面的代码:

        var val1 = ExtractValue(firstParam);
        var val2 = ExtractValue(secondParam);

        var type1 = val1.GetType();
        var type2 = val2.GetType();

        TypeConverter converter1 = TypeDescriptor.GetConverter(type1);
        TypeConverter converter2 = TypeDescriptor.GetConverter(type2);

        if (converter1 != null && converter1.CanConvertFrom(type2))
        {
            var temp = converter1.ConvertFrom(val2);
            return val1.Equals(temp);
        }
        return false;

it is a mystery for me that this code does not return true when I try it with a "int" and an Enum object. 对我来说,当我使用“int”和Enum对象尝试它时,此代码不会返回true,这是一个谜。 I even tried "val1.Equals((int)(val2))" in Immediate Window and the result was true but still the converter1.CanConvertFrom(type2) is false. 我甚至在立即窗口中尝试了“val1.Equals((int)(val2))”并且结果为true但仍然是converter1.CanConvertFrom(type2)为false。

Could you please help me about it? 你能帮我解决一下吗? Is there something that I am missing? 有什么东西我错过了吗?

Thanks 谢谢

Generalized type conversion is quite poor and inconsistent (in my opinion) in .NET. 在.NET中,广义类型转换非常差并且不一致(在我看来)。 However for the Enum / int case, you can use the IConvertible interface, or the Convert associated utility class: 但是对于Enum / int情况,您可以使用IConvertible接口或转换关联实用程序类:

int converted = (int)Convert.ChangeType(MyEnum.MyValue, typeof(int));

or 要么

object converted = Convert.ChangeType(myValue, myExpectedType);

As a site note, this 100% free library here: CodeFluentRuntimeClient has a class named ConvertUtilities that has a bunch of ChangeType method overloads (including a generic one) that are very versatile and useful for type conversion. 作为一个站点说明,这里有100%免费的库: CodeFluentRuntimeClient有一个名为ConvertUtilities的类,它有一堆ChangeType方法重载(包括一个通用的),它们非常通用,对类型转换很有用。

Note the remarks in the documentation : 请注意文档中的备注:

As implemented in this class, this method always returns false . 正如在此类中实现的,此方法始终返回false It never returns true . 它永远不会回归true

The only time you'll get back a different answer is if you have a derivative of TypeConverter . 如果你有TypeConverter的衍生产品,你唯一能回到不同答案的时间。 But it's important to note that a lot of the derivatives of TypeConverter in the Framework (say BaseNumberConverter do NOT override CanConvertFrom . 但重要的是要注意框架中TypeConverter的许多衍生物(比如说BaseNumberConverter不会覆盖CanConvertFrom

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM