Can't understand the Exception when using dynamic with generic collection in .net4

試著忘記壹切 提交于 2019-12-10 13:45:38

问题


check the code below please:

static void Main(string[] args) {
    IList<dynamic> items = new List<dynamic>();
    items.Add(3);
    items.Add("solid");
    dynamic i = new ExpandoObject();
    items.Add(i); //System.Collections.Generic.IList<object>' does not contain a definition for 'Add'
    Console.WriteLine();
}

is this a bug in "dynamic" mechanism?


回答1:


Looks like a bug (or is it a feature request?):

https://connect.microsoft.com/VisualStudio/feedback/details/534288/ilist-dynamic-cannot-call-a-method-add-without-casting




回答2:


This should do the trick:

static void Main(string[] args) {
    IList<dynamic> items = new List<dynamic>();
    items.Add(3);
    items.Add("solid");
    dynamic i = new ExpandoObject();
    items.Add((object) i); // type-cast dynamic object
    Console.WriteLine();
}


来源:https://stackoverflow.com/questions/7996491/cant-understand-the-exception-when-using-dynamic-with-generic-collection-in-ne

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