问题
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