简体   繁体   中英

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. I even tried "val1.Equals((int)(val2))" in Immediate Window and the result was true but still the converter1.CanConvertFrom(type2) is 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. However for the Enum / int case, you can use the IConvertible interface, or the Convert associated utility class:

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.

Note the remarks in the documentation :

As implemented in this class, this method always returns false . It never returns true .

The only time you'll get back a different answer is if you have a derivative of TypeConverter . But it's important to note that a lot of the derivatives of TypeConverter in the Framework (say BaseNumberConverter do NOT override CanConvertFrom .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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