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

蹲街弑〆低调 提交于 2020-01-02 02:34:54

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/7277108/access-to-private-method-using-reflection-in-c-silverlight-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!