您必须查看所有可能定义扩展方法的程序集。
查找装饰
ExtensionAttribute有的类,然后查找该类中
也 装饰有的方法
ExtensionAttribute。然后检查第一个参数的类型,以查看它是否与您感兴趣的类型匹配。
这是一些完整的代码。可能更严格(它不是检查类型是否嵌套,或者没有至少一个参数),但它应该给您帮助。
using System;using System.Runtime.CompilerServices;using System.Reflection;using System.Linq;using System.Collections.Generic;public static class FirstExtensions{ public static void Foo(this string x) {} public static void Bar(string x) {} // Not an ext. method public static void Baz(this int x) {} // Not on string}public static class SecondExtensions{ public static void Quux(this string x) {}}public class Test{ static void Main() { Assembly thisAssembly = typeof(Test).Assembly; foreach (MethodInfo method in GetExtensionMethods(thisAssembly, typeof(string))) { Console.WriteLine(method); } } static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly, Type extendedType) { var query = from type in assembly.GetTypes() where type.IsSealed && !type.IsGenericType && !type.IsNested from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where method.IsDefined(typeof(ExtensionAttribute), false) where method.GetParameters()[0].ParameterType == extendedType select method; return query; }}


