Reputation: 488
I have an extension method on string class
public static bool Contains(this string original, string value, StringComparison comparisionType)
{
return original.IndexOf(value, comparisionType) >= 0;
}
But impossible to get the method by reflection
IEnumerable<MethodInfo> foundMethods = from q in typeof(string).GetMethods()
where q.Name == "Contains"
select q;
foundMethods only obtain the Contains(string) method why? Where are the other Contains methods?
Upvotes: 1
Views: 451
Reputation: 3952
Your Contains Method is not in String class, therefore , you cannot obtain Contains method with typeof(string).GetMethods().
To obtain what you need you can use code
public partial String
{
public static bool Contains(this string original, string value, StringComparison comparisionType)
{
return original.IndexOf(value, comparisionType) >= 0;
}
}
But code has a problem that String class cannot be static so you cannot use this parameter.
So your should define this Contains method in any static Class.
you can obtain with using code:
public static StringDemo
{
public static bool Contains(this string original, string value, StringComparison comparisionType)
{
return original.IndexOf(value, comparisionType) >= 0;
}
}
IEnumerable<MethodInfo> foundMethods = from q in typeof(StringDemo).GetMethods()
where q.Name == "Contains"
select q;
Upvotes: 0
Reputation: 24403
You cannot use the simple reflection method you have listed in the question to find extension methods.
You will have to look at ExtensionAttribute on classes and methods and verify that the first parameter type is string. As as extension method can be defined in any assembly you will have to do this for assemblies of interest
Upvotes: 1
Reputation: 292445
It's not a method declared in the String
class, so GetMethods
can't see it. The fact that an extension method is in scope depends on whether the namespace that declares it is imported, and reflection doesn't know anything about that. Keep in mind that extension are just static methods, with syntactic sugar that makes it look like they are instance methods.
Upvotes: 3