2013-03-23 105 views
0

關於爲什麼varforeach循環中選取object類型有很多問題(123),但這一次不同。當我使用此代碼片段循環訪問X509Certificate2Collection時,令我感到驚訝的是,var實際上拾取了X509Certificate2類型,而不是object,儘管X509Certificate2Collection僅實現非泛型IEnumerable而不是IEnumerable<T>爲什麼var在X509Certificate2Collection循環中推斷類型X509Certificate2而不是對象?

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

你可以看到繼承層次的msdn article,但它似乎並沒有被實施IEnumerable<X509Certificate2>。如果我使用LINQ的收集,我沒有得到X509Certificate2類型:

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

那麼編譯器如何知道在var情況下的實際類型?

回答

3

X509Certificate2Collection.getEnumerator()返回X509Certificate2Enumerator,其中Current類型爲X509Certificate2

換句話說,c#不僅僅依靠IEnumerable或IEnumerable < T>。它正在直接查看該Current屬性。

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

+0

你可能是對的。這可以解釋它。謝謝! – 2013-03-23 01:01:35

+0

修改了鏈接到文檔 – 2013-03-23 01:08:14

相關問題