How to check assignability of types at runtime in C#?

后端 未结 6 1186
后悔当初
后悔当初 2021-02-06 02:11

The Type class has a method IsAssignableFrom() that almost works. Unfortunately it only returns true if the two types are the same or the first is in

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-06 02:39

    It actually happens to be the case that the decimal type is not "assignable" to the int type, and vice versa. Problems occur when boxing/unboxing gets involved.

    Take the example below:

    int p = 0;
    decimal d = 0m;
    object o = d;
    object x = p;
    
    // ok
    int a = (int)d;
    
    // invalid cast exception
    int i = (int)o;
    
    // invalid cast exception
    decimal y = (decimal)p;
    
    // compile error
    int j = d;
    

    This code looks like it should work, but the type cast from object produces an invalid cast exception, and the last line generates a compile-time error.

    The reason the assignment to a works is because the decimal class has an explicit override on the type cast operator to int. There does not exist an implicit type cast operator from decimal to int.

    Edit: There does not exist even the implicit operator in reverse. Int32 implements IConvertible, and that is how it converts to decimal End Edit

    In other words, the types are not assignable, but convertible.

    You could scan assemblies for explicit type cast operators and IConvertible interfaces, but I get the impression that would not serve you as well as programming for the specific few cases you know you will encounter.

    Good luck!

提交回复
热议问题