Skip to main content
 首页 » 编程设计

c#之反射扩展法

2024年02月23日13birdshome

我有一个字符串类的扩展方法

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为什么只获取Contains(string)方法?其他 Contains 方法在哪里?

请您参考如下方法:

它不是在 String 类中声明的方法,所以 GetMethods 看不到它。扩展方法在范围内的事实取决于声明它的命名空间是否被导入,而反射对此一无所知。请记住,扩展只是静态方法,带有使它们看起来像是实例方法的语法糖。