私有成员的后期绑定调用会抛出 MethodAccessException
我遇到了一个恼人的情况,即使我完全信任地运行代码,方法的后期绑定调用也会抛出 MethodAccessException 。情况如下:
我有一个基类,它按照约定映射一些事件处理逻辑,这些处理程序是使用通过发出 IL 代码创建的动态方法来调用的,遵循本教程: http://www.codeproject.com/KB/cs/dynamicmethoddelegates.aspx
//in AssemblyA.dll:
public abstract class Base : IEventHandler
{
protected static void RegisterDerivedType(Type derived)
{
//create list of delegates to invoke event handlers
}
void IEventHandler.Handle(IEvent e)
{
//late bound invocation of appropriate handler method (e.g. EventX
//or EventY)
//this code throws a MethodAccessException
}
}
//in assemblyB.dll
public class Derived : Base
{
static Derived()
{
RegisterDerivedType(typeof(Derived));
}
private void OnEventX(EventX e) //EventX is derived of IEvent
{ }
private void OnEventY(EventY e) //EventY is derived of IEvent
{ }
}
为什么我无法调用私有成员动态的 方法?
I have an annoying situation where the late bound invocation of a method throws a MethodAccessException even though I run the code in full trust. The situation is as follows:
I have a base class, which maps some event handling logic by convention, these handlers are invoked using dynamic methods created by emitting IL code, following this tutorial: http://www.codeproject.com/KB/cs/dynamicmethoddelegates.aspx
//in AssemblyA.dll:
public abstract class Base : IEventHandler
{
protected static void RegisterDerivedType(Type derived)
{
//create list of delegates to invoke event handlers
}
void IEventHandler.Handle(IEvent e)
{
//late bound invocation of appropriate handler method (e.g. EventX
//or EventY)
//this code throws a MethodAccessException
}
}
//in assemblyB.dll
public class Derived : Base
{
static Derived()
{
RegisterDerivedType(typeof(Derived));
}
private void OnEventX(EventX e) //EventX is derived of IEvent
{ }
private void OnEventY(EventY e) //EventY is derived of IEvent
{ }
}
Why is it not possible for me to invoke private members with a dynamic method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DynamicMethod
仍然遵循规则!要使其弯曲它们,您必须(在创建DynamicMethod
时)将owner
参数指定为声明私有方法的类型;那么你就可以有效地奔跑,就好像你属于那种类型一样。所以:(或任何接受
所有者
的类似重载)DynamicMethod
still follows the rules! To make it bend them, you must (when creating theDynamicMethod
) specify theowner
parameter as the type that declares the private method; then you are effectively running as though you were inside that type. So:(or any of the similar overloads that accept an
owner
)