作品
private void Add<H>(H toAdd, IList<dynamic> list)
{
list.Add(toAdd);
}
不工作
private void Add<H>(IList<H> toAdd, IList<IList<dynamic>> list)
{
list.Add(toAdd);
}
可以想象,错误是
The best overloaded method match for 'System.Collections.Generic.ICollection<System.Collections.Generic.IList<dynamic>>.Add(System.Collections.Generic.IList<dynamic>)' has some invalid arguments
如果有人知道为什么会发生这种情况甚至更好,如何解决它,我很好奇。我认为它与通用方差有关,但动态让我不太确定。
谢谢,汤姆
编辑
//doesn't work
private void Add<H>(IList<H> toAdd, IList<IList<dynamic>> list) where H : object
{
list.Add(toAdd);
}
//works
//this isn't good enough however because I only want to be able to
//have one type of object in toAdd
private void Add(IList<object> toAdd, IList<IList<dynamic>> list)
{
list.Add(toAdd);
}
//works
private void Add<H>(IList<H> toAdd, IList<IList<dynamic>> list)
{
list.Add(toAdd.Cast<dynamic>().ToList());
}
private void Foo()
{
//works
IList<dynamic> list1 = new List<object>();
//works
IList<object> list2 = new List<dynamic>();
//works
IList<IList<dynamic>> list4 = new List<IList<object>>();
//works
IList<IList<object>> list3 = new List<IList<dynamic>>();
}
我添加了更多示例(并不令人惊讶)只是为了说明