【问题标题】:Implicit version of IsAssignableFrom?IsAssignableFrom 的隐式版本?
【发布时间】:2010-01-15 23:39:28
【问题描述】:

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

if (f.FieldType.IsAssignableFrom("".GetType()))

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

【问题讨论】:

    标签: c# .net reflection implicit-conversion


    【解决方案1】:

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

    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;
        }
    }
    

    【讨论】:

    • 是的。隐式转换运算符只是语法糖。它们对 CLR 没有任何特殊意义,而且 VB.NET 甚至不理解它们(或者至少在过去不理解)。这不是真正的演员表,因此不是真正可分配的;唯一的答案是实际检查隐式运算符。
    【解决方案2】:
    if(... || TypeDescriptor.GetConverter(f).CanConvertTo("".GetType()))
    

    【讨论】:

    • 这里的问题是它似乎将一切都转换为字符串。包括非隐式类。它将类转换为字符串的事实破坏了我的代码。
    • 根据定义,所有对象都实现一个 ToString() 方法。
    猜你喜欢
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多