简体   繁体   中英

Reflection and extension method

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?

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.

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM