使用Xamarin / Mono为Android(以及后来的iOS)开发应用程序。通常我使用此代码来调用非静态泛型方法,它很有效:
serverService.GetCustomListObject<T> (firstRequestInLine,
null,
onGetCustomListObjectFromThread<T>,
onGetCustomListObjectFromThreadError);
其中回调定义为:
private void onGetCustomListObjectFromThread<T> (List<T> list,
RequestStateGen<T>.SuccessfullDelegateType successDel
{ ... }
和
private void onGetCustomListObjectFromThreadError (String error,
WebRequest failedRequest)
{ ... }
但是,现在我需要调用GetCustomListObject<t>
动态设置t
。我对泛型非常陌生,但是从其他示例中尝试了以下代码却没有成功:
typeof(ServerService).GetMethod ("GetCustomListObject").MakeGenericMethod (t).Invoke (serverService, new object[] {
firstRequestInLine,
null,
typeof(LocalServerService).GetMethod ("onGetCustomListObjectFromThread").MakeGenericMethod (t),
typeof(LocalServerService).GetMethod ("onGetCustomListObjectFromThreadError")
});
其中LocalServerService
是我的所有示例所在的类,而serverService
的类型为ServerService
我收到以下错误:
Error: Ambiguous matching in method resolution
编辑: ServerService中的GetCustomListObject:
public void GetCustomListObject<T> (WebRequest request,
RequestStateGen<T>.SuccessfullDelegateType successDelegate,
RequestStateGen<T>.InternalSuccessDelegateType internalSuccessDelegate,
RequestStateGen<T>.ErrorDelegateType errorDelegate)
答案 0 :(得分:1)
在原始代码中,您正在调用传递委托的方法。
在您的反思代码中,您似乎传递了MethodInfo
值 - 我不相信它们会自动转换为代理。
不幸的是,如果不知道GetCustomListObject
方法的声明就很难提供一个好的代码示例,但是你想要某些东西:
Type thirdArgType = typeof(Foo<>).MakeGenericGenericType(t);
MethodInfo thirdArgMethod = typeof(LocalServerService)
.GetMethod("onGetCustomListObjectFromThread",
BindingFlags.Instance | BindingFlags.NonPublic)
.MakeGenericMethod(t);
Delegate thirdArg = Delegate.CreateDelegate(thirdArgType, this, thirdArgMethod);
MethodInfo fourthArgMethod = typeof(LocalServerService)
.GetMethod("onGetCustomListObjectFromThreadError",
BindingFlags.Instance | BindingFlags.NonPublic);
Delegate fourthArg = Delegate.CreateDelegate(typeof(Bar), this, fourthArgMethod);
MethodInfo method = typeof(ServerService).GetMethod("GetCustomListObject")
.MakeGenericMethod (t);
method.Invoke(serverService,
new object[] {firstRequestInline, null, thirdArg, fourthArg });