英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论