我怎样才能确定是否在C#中存在隐式转换?

问题描述:

我有两种类型,T和U,我想知道隐式转换符是从T定义至U

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

我知道的存在 IsAssignableFrom , ,这是不是我要找的,因为它不隐式转换处理

I'm aware of the existence of IsAssignableFrom, and this is not what I'm looking for, as it doesn't deal with implicit casts.

谷歌搜索的带领我的这个解决方案,但在作者自己的话说,这是丑陋的代码(它会尝试投含蓄,如果有异常返回false,否则真...)

A bit of googling led me to this solution, but in the author's own words this is ugly code (it tries to cast implicitly and returns false if there's an exception, true otherwise...)

这似乎与正确的签名的won't基本类型的工作。

It seems testing for the existence of an op_Implicit method with the correct signature won't work for primitive types.

有确定隐式转换操作符的存在一个更清洁的方式?

Is there a cleaner way of determining the existence of an implicit cast operator?

您可以使用反射找到了隐式转换方法目标类型:

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.