Why is RuntimeBinderException thrown when generic parameter is private?

做~自己de王妃 提交于 2019-12-12 17:23:44

问题


When a method is called with a dynamic parameter of the form Foo<Bar>, a RuntimeBinderException is thrown when Bar is private. Why? (See comment in Run method of Test1 below.)

public class Test1
{
    public void Run()
    {
        dynamic publicList = ListProvider.GetPublic();
        DoSomething(publicList);

        dynamic privateList = ListProvider.GetPrivate();
        DoSomething(privateList); // Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
    }

    private void DoSomething<T>(List<T> list) { }

    static private class ListProvider
    {
        static public object GetPrivate() { return new List<A>(); }
        static public object GetPublic() { return new List<B>(); }

        private class A { }
        public class B { }
    }
}

To see why this is unreasonable/inconsistent, note that Test2 below, does not use generics, and succeeds when dynamic parameter is private.

public class Test2
{
    public void Run()
    {
        dynamic publicItem = ItemProvider.GetPublic();
        DoSomething(publicItem);

        dynamic privateItem = ItemProvider.GetPrivate();
        DoSomething(privateItem); // No exception thrown
    }

    private void DoSomething<T>(T t) { }

    static private class ItemProvider
    {
        static public object GetPrivate() { return new A(); }
        static public object GetPublic() { return new B(); }

        private class A { }
        public class B { }
    }
}

Why would/should the use of generics affect the resolution of a dynamic parameter with respect to access modifiers?

来源:https://stackoverflow.com/questions/42012743/why-is-runtimebinderexception-thrown-when-generic-parameter-is-private

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