Can't understand the Exception when using dyna

2019-06-22 05:31发布

问题:

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();
}