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

后端 未结 6 1182
后悔当初
后悔当初 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条回答
  •  臣服心动
    2021-02-06 02:31

    This one almost works... it's using Linq expressions:

    public static bool IsReallyAssignableFrom(this Type type, Type otherType)
    {
        if (type.IsAssignableFrom(otherType))
            return true;
    
        try
        {
            var v = Expression.Variable(otherType);
            var expr = Expression.Convert(v, type);
            return expr.Method == null || expr.Method.Name == "op_Implicit";
        }
        catch(InvalidOperationException ex)
        {
            return false;
        }
    }
    

    The only case that doesn't work is for built-in conversions for primitive types: it incorrectly returns true for conversions that should be explicit (e.g. int to short). I guess you could handle those cases manually, as there is a finite (and rather small) number of them.

    I don't really like having to catch an exception to detect invalid conversions, but I don't see any other simple way to do it...

提交回复
热议问题