ThanhNguyen
ThanhNguyen

Reputation: 85

How to call method by string name in Windows Phone


I have a string whose content is name of 1 function in my WP apps. For example, assume that I have:

string functionName = "button3_Click"

So I would like to call the button3_Click() in my apps. I tried the GetRuntimeMethod method in System.Reflection but the result returned is null, so when I use invoke I got the System.NullReferenceException. My code to call this function is:

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);

And the prototype of button3_Click is:

private void button3_Click(object sender, RoutedEventArgs e)

So how can I call the function whose name contained in the string? Thank you so much for you help.

Update
I can call the button3_Click() method by changing access level of this method to public, is there any way to keep access level of this method is private and I can call this method? Thank you for your help.
Finally
I think I should use the code like this, it can get all method even its access level is private or public:

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);

Thank you for your help.

Upvotes: 2

Views: 1522

Answers (2)

Alovchin
Alovchin

Reputation: 683

If your app is a Windows Runtime app, use GetTypeInfo extension method on thisType and then use TypeInfo.GetDeclaredMethod method:

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);

It is said in documentation that GetDeclaredMethod returns all public members of a type, but according to .NET Reference Source, the documentation seems to be incorrect: it calls Type.GetMethod with flags constant that contains BindingFlags.NonPublic.

Upvotes: 3

lisp
lisp

Reputation: 4198

There are restrictions on Silverlight reflection:

In Silverlight, you cannot use reflection to access private types and members. If the access level of a type or member would prevent you from accessing it in statically compiled code, you cannot access it dynamically by using reflection. (source)

Look into LambdaExpressions as it might be a workaround in this case.

Upvotes: 1

Related Questions