C# 如何在Windows Phone中按字符串名调用方法
C# 如何在Windows Phone中按字符串名调用方法,c#,windows-phone-8.1,C#,Windows Phone 8.1,我有一个字符串,其内容是我的WP应用程序中1个函数的名称。例如,假设我有: string functionName = "button3_Click" 因此,我想在我的应用程序中调用按钮3_Click()。我在System.Reflection中尝试了GetRuntimeMethod方法,但返回的结果为null,因此当我使用invoke时,我得到了System.NullReferenceException。我调用此函数的代码是: System.Type[] types = { typeof(M
我有一个字符串,其内容是我的WP应用程序中1个函数的名称。例如,假设我有:
string functionName = "button3_Click"
因此,我想在我的应用程序中调用按钮3_Click()。我在System.Reflection中尝试了GetRuntimeMethod方法,但返回的结果为null,因此当我使用invoke时,我得到了System.NullReferenceException。我调用此函数的代码是:
System.Type[] types = { typeof(MainPage), typeof(RoutedEventArgs) };
string functionName = "button3_Click";
System.Type thisType = this.GetType();
MethodInfo method = thisType.GetRuntimeMethod(functionName, types);
object[] parameters = {this, null};
method.Invoke(this, parameters);
button3\u Click的原型是:
private void button3_Click(object sender, RoutedEventArgs e)
那么,如何调用名称包含在字符串中的函数呢?非常感谢你的帮助
更新我可以通过将此方法的访问级别更改为public来调用button3\u Click()方法,有没有办法使此方法的访问级别保持私有,我可以调用此方法?谢谢你的帮助。
最后
我想我应该使用这样的代码,它可以获取所有方法,即使其访问级别是私有的或公共的:
System.Type[] types = { typeof(MainPage), typeof(RoutedEventArgs) };
string functionName = "button6_Click";
TypeInfo typeinfo = typeof(MainPage).GetTypeInfo();
MethodInfo methodinfo = typeinfo.GetDeclaredMethod(functionName);
object[] parameters = {this, null};
methodinfo.Invoke(this, parameters);
感谢您的帮助。Silverlight反射有以下限制: 在Silverlight中,不能使用反射来访问私有类型和成员。如果类型或成员的访问级别会阻止您在静态编译代码中访问它,则无法使用反射动态访问它。()
查看
LambdaExpressions
,因为这可能是本例中的一种解决方法。如果您的应用程序是Windows运行时应用程序,请使用此类型的扩展方法,然后使用方法:
文档中说,GetDeclaredMethod
返回某一类型的所有公共成员,但根据,文档似乎不正确:它使用包含BindingFlags的调用Type.GetMethod
。非公共的尝试在thisType
上使用方法,然后与BindingFlags.Instance | BindingFlags.NonPublic
标志一起使用。@Alovchin:我在TypeInfo对象中看不到GetMethod。也许我必须使用GetRuntimeMethod,但我需要一种获取私有方法的方法。谢谢你的帮助,我使用GetDeclaredMethod,现在对我来说没问题。你确定GetDeclaredMethod会返回私有方法的MethodInfo吗?@Alovchin:是的,我试过了。我可以同时获得public方法和private方法:)但应用程序似乎是在Windows运行时编写的。@Alovchin你确定吗GetMethod()
由于某些原因不可用。@Madscher据我所知,在Windows运行时应用程序中,System.Type
类是类的投影,因此它不包含太多.NET的System.Type成员。为了访问更多的函数,应该调用我在回答中提到的GetTypeInfo
方法,并使用System.Reflection.TypeInfo
对象。@Alovchin:我在TypeInfo对象中看不到GetMethod。也许我必须使用GetRuntimeMethod,但我需要一种获取私有方法的方法。我在一个可移植类库中尝试了GetDeclaredMethod,它只返回公共方法。
using System.Reflection;
...
System.Type thisType = this.GetType();
TypeInfo thisTypeInfo = thisType.GetTypeInfo();
MethodInfo method = thisTypeInfo.GetDeclaredMethod(functionName);
object[] parameters = {this, null};
method.Invoke(this, parameters);