0

关于为什么在循环中选择类型有很多问题(1 2 3 ) ,但这次不同。当我使用此代码片段循环 a时,令我惊讶的是,实际上选择了类型,而不是,尽管只实现了非泛型而不是!varobjectforeachX509Certificate2CollectionvarX509Certificate2objectX509Certificate2CollectionIEnumerableIEnumerable<T>

X509Certificate2Collection collection = new X509Certificate2Collection();
foreach (var cert in collection)
{
    Console.WriteLine(cert.Subject);
}

您可以在msdn 文章中看到继承层次结构,但它似乎没有实现IEnumerable<X509Certificate2>。如果我在集合上使用 LINQ,我不会得到X509Certificate2类型:

collection.Select(cert => cert.Subject); // Won't compile

那么编译器如何知道var案例中的实际类型呢?

4

1 回答 1

3

X509Certificate2Collection.getEnumerator()返回一个X509Certificate2Enumerator,它有一个Current类型的属性X509Certificate2

换句话说,c# 不仅仅依赖于 IEnumerable 或 IEnumerable<T>。它直接查看该Current属性。

http://msdn.microsoft.com/en-us/library/aa288257%28v=vs.71%29.aspx

于 2013-03-23T00:56:25.073 回答