简体   繁体   中英

Late-bound invocation of private member throws a MethodAccessException

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?

DynamicMethod still follows the rules! To make it bend them, you must (when creating the DynamicMethod ) specify the owner parameter as the type that declares the private method ; then you are effectively running as though you were inside that type. So:

var method = new DynamicMethod(
      name, returnType, parameterTypes, declaringType, true);

(or any of the similar overloads that accept an owner )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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