7

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

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

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

4

2 回答 2

9

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

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;
    }
}
于 2010-01-16T02:30:23.827 回答
0
if(... || TypeDescriptor.GetConverter(f).CanConvertTo("".GetType()))
于 2010-01-15T23:59:49.687 回答