Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to private method using reflection in C#/Silverlight applications

My code invokes method using reflection:

        scoringType.InvokeMember("scoringClient_ScorePostsCompleted",
            BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
            null, scoringInstance,
            new object[] { sArg, eArg });

where scoringInstance is an instance of a ModelView class. The method is private, but I use BindingFlags.NonPublic, so, i should be able to access it, but I cannot - I get MethodAccessException exception: "Attempt by method ... to access method ... failed." Google doesnt seem to have an answer. Do you have any idea how to fix it by any chance?

like image 408
Val Avatar asked Sep 01 '11 22:09

Val


People also ask

Can we access private methods using reflection C#?

So, just focus on typeof, getMethod and Invoke functions etc. Using reflection in C# language, we can access the private fields, data and functions etc.

Can we access private method using object?

Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class.


2 Answers

From MSDN on silverlight

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.

Edit:

Silverlight 5 now does allow for reflection of private members ONLY if you're running with elevated privileges either out-of-browser or in-browser (in-browser using the generated test page DOES NOT WORK).

like image 171
MerickOWA Avatar answered Sep 24 '22 09:09

MerickOWA


If you need access to non-public members, you can do this using the LambdaExpression. I wrote this article that explains in detail why it works.

like image 24
Vyacheslav Volkov Avatar answered Sep 23 '22 09:09

Vyacheslav Volkov