如何将此片段更改以正确地将 A
的实例添加到 List<A>
,B
添加到 List<B>
等等?
// someChild's actual type is A
object someChild = GetObject();
// collection's actual type is List<A> though method below returns object
dynamic list = GetListFromSomewhere(...);
// code below throws a RuntimeBinderException
list.Add(somechild);
异常被抛出是因为绑定器找到了
Add()
,但它传入了 dynamic
,导致重载决议失败。我更倾向于 不 改变上述内容并使用反射,或者至少将其最小化。我可以访问每个 A
和 List<A>
的 System.Type
实例。包含上述代码的类或方法本身不是泛型。