2011-12-19 77 views
1

我有串类反思与扩展方法

public static bool Contains(this string original, string value, StringComparison comparisionType) 
{ 
    return original.IndexOf(value, comparisionType) >= 0; 
} 

但不可能扩展方法通过反射来获取的方法

IEnumerable<MethodInfo> foundMethods = from q in typeof(string).GetMethods() 
             where q.Name == "Contains" 
             select q; 

foundMethods仅获得包含(string)方法,为什么?其他包含方法在哪里?

+2

[C#反射来标识扩展方法(可能重复http://stackoverflow.com/questions/299515/c-sharp-reflection-to-identify -extension-methods) – 2011-12-19 14:09:16

+0

[Reflection to Identify Extension Methods]的可能重复(http://stackoverflow.com/questions/299515/reflection-to-identify-extension-methods) – 2017-04-13 14:35:00

回答

3

这不是在String类中声明的方法,所以GetMethods看不到它。扩展方法在范围内的事实取决于声明它的名称空间是否已导入,并且反射对此没有任何了解。请记住,扩展只是静态方法,语法糖使它看起来像是实例方法。

1

您不能使用问题中列出的简单反射方法查找扩展方法。

你将不得不看ExtensionAttribute的类和方法,并验证第一个参数类型为字符串。由于作为扩展方法可以在任何组件定义你将不得不感兴趣

0

组件做到这一点你包含方法是不是在String类,因此,你不能获得包含方法用typeof(串).GetMethods()。

为了得到你需要,你可以使用代码

public partial String 
{ 
    public static bool Contains(this string original, string value, StringComparison comparisionType) 
    { 
     return original.IndexOf(value, comparisionType) >= 0; 
    } 
} 

但代码有,所以你不能使用此参数String类不能是静态的问题是什么。

所以你应该在任何静态类中定义这个Contains方法。

您可以使用代码获取:

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;