How can I determine if an implicit cast exists in C#?

后端 未结 3 1471
予麋鹿
予麋鹿 2021-02-18 13:16

I have two types, T and U, and I want to know whether an implicit cast operator is defined from T to U.

I\'m aware of the existence of IsAssignableFrom, and this is not

3条回答
  •  忘掉有多难
    2021-02-18 14:05

    You could use reflection to find the implicit conversion method for the target type:

    public static bool HasImplicitConversion(Type baseType, Type targetType)
    {
        return baseType.GetMethods(BindingFlags.Public | BindingFlags.Static)
            .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType)
            .Any(mi => {
                ParameterInfo pi = mi.GetParameters().FirstOrDefault();
                return pi != null && pi.ParameterType == baseType;
            });
    }
    

    You can use it like this:

    class X {}
    class Y
    {
        public static implicit operator X (Y y)
        {
            return new X();
        }
    
        public static implicit operator Y (X x)
        {
            return new Y();
        }
    }
    
    // and then:
    bool conversionExists = HasImplicitConversion(typeof(Y), typeof(X));
    

    Note that this only checks for an implicit type conversion on the base type (the first passed type). Technically, the type conversion can also be defined on the other type, so you may need to call it again with the types reversed (or build that into the method). Implicit type conversions may not exist on both types though.

提交回复
热议问题