简体   繁体   中英

C# dynamic and working with IEnumerable collections

After encountering some problems with Massive today, I decided to create a simple test program to illustrate the problem. I wonder, what's the mistake I'm doing in this code:

var list = new List<string>
               {
                   "Hey"
               };

dynamic data = list.Select(x => x);

var count = data.Count();

The last line throws an error: 'object' does not contain a definition for 'Count'

Why is the "data" treated as an object? Does this problem occur because I'm calling an extension method?

The following code works:

var list = new List<string>
               {
                   "Hey"
               };

dynamic data = list.Select(x => x);

foreach (var s in data)
{
}

Why in this case "data" is correctly treated as IEnumerable?

Yes, that's because Count() is an extension method.

extension methods aren't supported by dynamic typing in the form of extension methods, ie called as if they were instance methods. ( source )

foreach (var s in data) works, because data has to implements IEnumerable to be a foreach source - there is (IEnumerable)data conversion performed during execution.

You can see that mechanish when trying to do following:

dynamic t = 1;

foreach (var i in t)
    Console.WriteLine(i.ToString());

There is an exception thrown at runtime: Cannot implicitly convert type 'int' to 'System.Collections.IEnumerable'

Seems that extension methods do not work on dynamic objects (see Jon' answer ). However, you can call those directly as static methods:

var count = Enumerable.Count(data); // works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM