使用反射来调用泛型方法

问题描述 投票:1回答:1

我的代码中有一个字符串变量,我需要用它来调用Xamarin表单项目中的泛型方法来进行页面导航。

我的初始代码。

 string currentPage = SelectedFunction.PageName;
 var abc1 = Type.GetType(currentPage);
 CoreMethods.SwitchSelectedTab<abc>();

但在做了一些研究并与一些人交谈之后,我明白我们不能以这种方式初始化泛型方法,因为Type需要在编译时设置。经过一些进一步的研究,我了解到我们可以使用反射API实现这一点。我试了一下。

这是我当前的代码版本。

var currentPage = SelectedFunction.PageModelName;
var abc1 = Type.GetType(currentPage);
MethodInfo method = typeof(PageModelCoreMethods).GetTypeInfo().GetDeclaredMethod("SwitchSelectedTab");

        MethodInfo generic = method.MakeGenericMethod(abc1);
generic.Invoke(new PageModelCoreMethods(CurrentPage, this), null);

代码编译正确但导航不会发生。

关于我调用的泛型方法的一些进一步信息:该方法在nuget包中。以下是该类的github链接:https://github.com/rid00z/FreshMvvm/blob/d1c9e1896e4040388ef43203df1254787bc84f36/src/FreshMvvm/PageModelCoreMethods.cs

编辑1

在约翰的建议之后我查看了我的代码。而他是对的,我的逻辑绝对不正确。

这是我想要实现的(静态完成时工作)

var currentPage = SelectedFunction.PageName;
var abc1 = Type.GetType(currentPage);
CoreMethods.SwitchSelectedTab<HomeViewModel>();
CoreMethods.PushPageModel<RefreshLocationItemPageModel>();

以前,我正在尝试CoreMethods.SwitchSelectedTab();.所以我编辑了我的代码

var currentPage = SelectedFunction.PageName;
var abc1 = Type.GetType(currentPage);
CoreMethods.SwitchSelectedTab<HomeViewModel>();
MethodInfo method = typeof(PageModelCoreMethods).GetTypeInfo().GetDeclaredMethod("PushPageModel");
MethodInfo generic = method.MakeGenericMethod(abc1);
generic.Invoke(CoreMethods, null);

但是当我这样做时,我得到了一个例外。

{System.Reflection.AmbiguousMatchException: Ambiguous match found.
at System.RuntimeType.GetMethodImpl (System.String name, 
System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder 
binder, System.Reflection.CallingConventions callConv, System.Type[] 
types, System.Reflection.ParameterModifier[] modifiers) [0x00059] in 
<f32579baafc1404fa37ba3ec1abdc0bd>:0 
at System.Type.GetMethod (System.String name, 
System.Reflection.BindingFlags bindingAttr) [0x0000e] in 
<f32579baafc1404fa37ba3ec1abdc0bd>:0 
at System.Reflection.TypeInfo.GetDeclaredMethod (System.String name) 
[0x00000] in <f32579baafc1404fa37ba3ec1abdc0bd>:0 
at 

********。州内的/Manager*/Functions/StateManager/PausedFunctionPageModel.cs:55中的StateManager.PausedFunctionPageModel.NavigateToFunction()[0x00020]。Functions.StateManager.PausedFunctionPageModel。 set_SelectedFunction(*******。Common.Models.PageState value)[0x00022] in /********/Functions/StateManager/PausedFunctionPageModel.cs:29 at(wrapper managed-to-native)系统System.Reflection.MonoMethod.Invoke中的.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object [],System.Exception&)(System.Object obj,System.Reflection.BindingFlags invokeAttr,System.Reflection.Binder binder ,System.Object []参数,System.Globalization.CultureInfo文化)[0x00032] in:0}

c# xamarin reflection
1个回答
1
投票

有多个PushPageModel方法。其中一个采用一个通用参数,另一个采用两个。我建议你使用GetDeclaredMethods()(带有s)并迭代结果。

© www.soinside.com 2019 - 2024. All rights reserved.