Implicit version of IsAssignableFrom?
In my code using reflections i wrote
if (f.FieldType.IsAssignableFrom("".GetType()))
I have a class that has an implicit conversion to strings. However the if statement above doesnt catch it. How can i make reflection/the above if statemen开发者_StackOverflowt catch strings and classes with implicit string conversion? instead of specifically strings and each class i know about?
I would use an extension method which gets all public static methods and checks for a method with the correct name and return type.
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;
}
}
if(... || TypeDescriptor.GetConverter(f).CanConvertTo("".GetType()))
精彩评论