简体   繁体   English

C#动态并使用IEnumerable集合

[英]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. 在今天遇到Massive的一些问题后,我决定创建一个简单的测试程序来说明问题。 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' 最后一行抛出错误: 'object'不包含'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? 为什么在这种情况下“数据”被正确地视为IEnumerable?

Yes, that's because Count() is an extension method. 是的,那是因为Count()是一种扩展方法。

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. foreach (var s in data)工作,因为data 必须实现IEnumerable作为foreach源 - 在执行期间执行(IEnumerable)data转换。

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' 运行时抛出异常: Cannot implicitly convert type 'int' to 'System.Collections.IEnumerable'

Seems that extension methods do not work on dynamic objects (see Jon' answer ). 似乎扩展方法不适用于动态对象(请参阅Jon的回答 )。 However, you can call those directly as static methods: 但是,您可以直接将它们称为静态方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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