隐含版本的IsAssignableFrom?

6 .net c# reflection implicit-cast

在我的代码中使用我写的反射

if (f.FieldType.IsAssignableFrom("".GetType()))
Run Code Online (Sandbox Code Playgroud)

我有一个隐式转换为字符串的类.但是上面的if语句并没有抓住它.我如何使用隐式字符串转换来进行反射/上述if语句捕获字符串和类?而不是专门的字符串和我知道的每个类?

Cou*_*y D 7

我将使用一个扩展方法,它获取所有公共静态方法并检查具有正确名称和返回类型的方法.

public static class TypeExtentions
{
    public static bool ImplicitlyConvertsTo(this Type type, Type destinationType)
    {

        if (type == destinationType)
            return true;


        return (from method in type.GetMethods(BindingFlags.Static |
                                               BindingFlags.Public)
                where method.Name == "op_Implicit" &&
                      method.ReturnType == destinationType
                select method
                ).Count() > 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对.隐式转换运算符只是语法糖.它们对CLR没有任何特殊意义,VB.NET甚至不理解它们(或者至少它不是在过去).这不是一个真正的演员,因此它不是真正可转让的; 唯一的答案是实际检查隐式运算符. (3认同)