简体   繁体   English

在C#/ Silverlight应用程序中使用反射访问私有方法

[英]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. 其中scoringInstance是ModelView类的一个实例。 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." 该方法是私有的,但我使用BindingFlags.NonPublic,所以,我应该能够访问它,但我不能 - 我得到MethodAccessException异常:“尝试方法...访问方法...失败。” Google doesnt seem to have an answer. 谷歌似乎没有答案。 Do you have any idea how to fix it by any chance? 你知道如何解决这个问题吗?

From MSDN on silverlight 来自MSDN上的silverlight

In Silverlight, you cannot use reflection to access private types and members. 在Silverlight中,您无法使用反射来访问私有类型和成员。 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). Silverlight 5现在只允许私有成员的反映,如果您在浏览器外或浏览器中使用提升的权限运行(使用生成的测试页面在浏览器中不工作)。

If you need access to non-public members, you can do this using the LambdaExpression . 如果您需要访问非公共成员,可以使用LambdaExpression执行此操作。 I wrote this article that explains in detail why it works. 我写了这篇文章 ,详细解释了它的工作原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM