开发者

Why MemberAccessException not throwing?

simple code:

class Pr开发者_开发技巧ogram
{
    static void Main(string[] args)
    {
        A a = new A();

        //Expect MemberAccessException here
        //(http://msdn.microsoft.com/en-us/library/system.delegate.method.aspx)
        Console.WriteLine("Delegate.Method: " + a.ACallback.Method); 
        Console.ReadLine();
    }
}

public delegate void TestCallback();

class A
{
    public TestCallback ACallback;

    public A()
    {
        ACallback = new TestCallback(this.Some);
    }

    private void Some()
    {
        Console.WriteLine("Call Some");
    }
}

And didn't catch any exception, why?


from MSDN: Delegate.Method Property

MemberAccessException: The caller does not have access to the method represented by the delegate (for example, if the method is private).

but your A.ACallback is public.


It looks to me like your code is perfectly valid ... if you are expecting an exception to be thrown because you are trying to access a private member of the delegate your logic is incorrect. You are calling the private method via a public member of the class so this works just fine.

Making TestCallback private would result in a compile time error I'm not sure how you expect to generate a MemberAccessException?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜