【发布时间】:2012-02-13 06:09:44
【问题描述】:
如何更改此 sn-p 以正确地将 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,这导致重载解析失败。我更喜欢 not 将上述内容更改为使用反射,或者至少将其最小化。对于A 和List<A>,我确实可以访问System.Type 的实例。包含上述代码的类或方法本身不是泛型的。
【问题讨论】:
标签: c# dynamic collections casting