2014-02-24 83 views
0

當我注意到我的foreach循環無法上傳文件列表並且for循環沒有工作時,我正在使用我的網站。我很想知道for循環的工作原理和foreach循環的原因。上傳文件時出現Casting錯誤

我得到的錯誤消息是:無法將system.string轉換爲xx。

所以這些都是循環我有:

HttpFileCollection documentsList = Request.Files; 

// Doesn't 
foreach (var file in documentsList.Cast<HttpPostedFile>()) 
{ 
    var test = file; 
} 

// Doesn't 
foreach (var file in documentsList) 
{ 
    var test = (HttpPostedFile)file; 
} 

// Works 
for (int i = 0; i < documentsList.Count; i++) 
{ 
    var file = (HttpPostedFile) documentsList[i]; 
} 

提前感謝!

回答

2

只要你看看HttpFileCollection's documentation,它變得更清晰......

indexer有一個聲明的類型的HttpPostedFile。而GetEnumerator指出:

此枚舉器將集合的鍵作爲字符串返回。

所以基本上你的foreach循環遍歷集合中的鍵,而你想要的值。這本質上是一個奇怪的設計決定,在NameObjectCollectionBase

你可以使用:

foreach (var file in documentsList.Cast<string>() 
            .Select(key => documentsList[key])) 
{ 
    ... 
} 
+0

啊謝謝!我不知道 – Jamie

相關問題