如何在方法存在歧义时获取具有通用参数的静态方法的MethodInfo?

huangapple go评论66阅读模式
英文:

How to get MethodInfo of static method with generic parameters when method ambiguity occurs?

问题

以下是您要翻译的内容:

我想要获取的方法是来自 **System.Reactive**  `Observable.Return`。

它的定义如下:

```csharp
public static IObservable<TResult> Return<TResult>(TResult value)
{
    ...
}

我尝试了以下代码:

Type observableType = typeof(Observable);
MethodInfo returnMethodInfo = observableType.GetMethod("Return");
var genericMethodInfo = returnMethodInfo.MakeGenericMethod(typeof(int));

问题在于我得到了一个错误消息:

找到多个匹配项。

我猜这是因为还有另一个名为 "Return" 的方法:

public static IObservable<TResult> Return<TResult>(TResult value, IScheduler scheduler)
{
   ...
}

我应该如何调用 GetMethod 来获取我想要的方法的 MethodInfo

英文:

The method I would like to obtain is Observable.Return from System.Reactive.

It's defined like this:

public static IObservable<TResult> Return<TResult>(TResult value)
{
    ...
}

I've tried with

Type observableType = typeof(Observable);
MethodInfo returnMethodInfo = observableType.GetMethod("Return");
var genericMethodInfo = returnMethodInfo.MakeGenericMethod(typeof(int));

The problem is that I'm getting an error message:

> Ambiguous match found.

I guess it's because there is another method called "Return":

public static IObservable<TResult> Return<TResult>(TResult value, IScheduler scheduler)
{
   ...
}

How should I call GetMethod to get a MethodInfo to the method I want?

答案1

得分: 2

你可以尝试使用这个解决方案。

var method = typeof(Observable).GetMethods().FirstOrDefault(
    x => x.Name.Equals("Return", StringComparison.OrdinalIgnoreCase) &&
         x.IsGenericMethod && x.GetParameters().Length == 1)
?.MakeGenericMethod(typeof(int));
英文:

You could try it with this solution.

    var method = typeof(Observable).GetMethods().FirstOrDefault(
            x => x.Name.Equals("Return", StringComparison.OrdinalIgnoreCase) &&
                x.IsGenericMethod && x.GetParameters().Length == 1)
        ?.MakeGenericMethod(typeof(int));

答案2

得分: 1

你需要使用GetMethods()并筛选出你想要的方法;这可能会很简单,如下所示:

var returnMethodInfo = observableType.GetMethods().Single(x => x.Name == "Return"
    && x.IsGenericMethodDefinition && x.GetParameters().Length == 1);
英文:

You'll need to use GetMethods() and filter to the one you want; this could be as simple as:

var returnMethodInfo = observableType.GetMethods().Single(x => x.Name == "Return"
    && x.IsGenericMethodDefinition && x.GetParameters().Length == 1);

huangapple
  • 本文由 发表于 2023年3月3日 18:19:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定