c# - 查找 IEnumerable 对象的类型

标签 c#

对于我能做的大多数对象,

obj.getType().FullName

但是对于下面的代码,

static void Main(string[] args)
        {
            IEnumerable<int> em = get_enumerable();
            Console.WriteLine(em.GetType());
            Console.Read();
        }

        static IEnumerable<int> get_enumerable()
        {
            for (int i = 0; i < 10; i++)
            {
                yield return i;
            }
        }

输出是,

ConsoleApplication1.Program+d__0

其中 ConsoleApplication1 是程序集,Program 是包含类(未显示)。为什么它不显示 IEnumerable 以及如何使 GetType 对这种情况更具描述性?

最佳答案

IEnumerable<T>是一个开放通用类型。它不是实际类型;它只是一个构造具体(封闭)泛型类型的函数,如 IEnumerable<int> .

IEnumerable<int>是一个接口(interface);不可能有一个接口(interface)的实例。

您的迭代器函数实际上返回一个隐藏的编译器生成类的实例,该类实现了 IEnumerable<int> ;这就是你从 GetType() 看到的.

您想找到类型的 IEnumerable<T> 的泛型类型参数实现:

em.GetType().GetInterface("System.Collections.Generic.IEnumerable`1")
            .GetGenericArguments()[0]

关于c# - 查找 IEnumerable 对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17408380/

相关文章:

c# - 如何更新 ToggleButton 内容的颜色?

c# - 使用二项元组与字典相比有什么优势?

c# - 你调用的对象是空的。 (HttpContext.Current.Request)

c# - 为 RadioButtonList 项目添加工具提示

c# - LINQ:如何缩短我的代码?

c# - 多个光线转换,只有两个在工作

c# - 如何在 Windows 8 Metro C# XAML 应用程序中播放 H.264 RTSP 视频?

c# - 在 C# 中的函数调用之前设置标签的文本

c# - TLS 连接 : override certificate validation

c# - Elasticsearch 巢 : Bulk-indexing operation does not make use of specified document IDs