简体   繁体   English

如何通过扩展重载泛型方法的反映获得方法?

[英]how to get method through reflection of extension overloaded generic method?

public static M MustNotEqual<M, T, R>(this IMustPassRule<M, T, R> mpr, R value)
{
    return mpr.MustPassRule(new NotEqualRule<R>(value));
}

public static M MustNotEqual<M, T, R>(this IMustPassRule<M, T, R> mpr, R value, IEqualityComparer<R> comparer)
{
    return mpr.MustPassRule(new NotEqualRule<R>(value, comparer));
}

How to get through reflection first method for example? 例如如何通过反射优先法?

If the parameter wouldn't be generic type you could use this overload of GetMethod and pass a type array to match parameter types.In this case I would do it using linq: 如果参数不是通用类型,则可以使用this overload of GetMethod并传递类型数组以匹配参数类型。在这种情况下,我可以使用linq来实现:

yourType.GetMethods(BindingFlags.Static | BindingFlags.Public)
        .FirstOrDefault(m => m.Name == "MustNotEqual" &&
                             m.GetParameters().Length == 2);

Ofcourse you can improve this to match the parameter types, this is just an example.To see why GetMethod is not an option you can have a look at this question . 当然,您可以改进它以匹配参数类型,这只是一个示例。要了解为什么不使用GetMethod ,可以看一下这个问题

Finding the extension methods that apply to a class is quite tricky. 寻找适用于类的扩展方法非常棘手。 When you call an extension method the compiler will look at all the types in scope which have methods with an ExtensionAttribute on them. 当您调用扩展方法时,编译器将查看作用域中所有具有类型为ExtensionAttribute的方法的类型。 This extension is automatically added by the compiler when it compiles an extension method. 该扩展名由编译器在编译扩展方法时自动添加。

Trying to resolve them at runtime is difficult as there is no concept of what namespaces are in scope when your code executes - all you've got is your class and it isn't necessarily tied to the extension method. 尝试在运行时解析它们很困难,因为在执行代码时并没有定义范围内的名称空间的概念-您所拥有的只是您的类,并且不一定与扩展方法相关。 If you want to search a particular class for an extension method then that's easy, you just use GetMethod with the appropriate BindingFlags and check the Extension attribute if you want to be really thorough. 如果要在特定的类中搜索扩展方法,那很容易,您只需将GetMethod与相应的BindingFlags一起使用,并检查Extension属性(如果想真正实现)。 However, if this isn't the case then you'll need to enumerate all the assemblies currently loaded searching for public classes that have a static method with the Extension attribute that matches your parameter criteria. 但是,如果不是这种情况,那么您将需要枚举当前加载的所有程序集,以搜索具有静态方法且具有与参数条件匹配的Extension属性的公共类。

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

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