简体   繁体   English

反思和延伸方法

[英]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? foundMethods只获取Contains(string)方法为什么? Where are the other Contains methods? 其他包含方法在哪里?

It's not a method declared in the String class, so GetMethods can't see it. 它不是String类中声明的方法,因此GetMethods无法看到它。 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 . 您将不得不在类和方法上查看ExtensionAttribute并验证第一个参数类型是字符串 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(). 您的Contains方法不在String类中,因此,您无法使用typeof(string).GetMethods()获取Contains方法。

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. 但代码有一个问题,String类不能是静态的,所以你不能使用这个参数。

So your should define this Contains method in any static Class. 所以你应该在任何静态类中定义这个Contains方法。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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