2013-07-18 126 views
0

我有一個變量(我稱之爲道具),其類型是「對象」,我知道底層類型將永遠是某種ICollection。我想迭代這個集合,並且將所有元素都包含進去。C#對象運行時類型鑄造

我的prop變量有一個方法GetType(),它返回類型。

foreach (var item in prop as ICollection<PCNWeb.Models.Port>) 
{ 
    //do more cool stuff here 
} 

的問題是我不知道的內部類型的ICollection的是在編譯時什麼,(以上列出PCNWeb.Models.Port)。

調用prop.GetType().ToString()(在這種情況下)產生System.Collections.Generic.HashSet`1[PCNWeb.Models.Port]

我可以告訴大家的信息是沒有辦法,我需要的,只是不知道如何使它發揮作用。

我已經嘗試了一些東西(雖然也許不正確地):

嘗試1:

Type t = prop.GetType(); 
foreach (var item in Convert.ChangeType(prop, t)) 
{ 
    //do more cool stuff here 
} 

其中產量:

Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator' 

嘗試2:

Type t = prop.GetType(); 
foreach (var item in prop as t) 
{ 
     //do more cool stuff here 
} 

其中產量:

Compiler Error Message: CS0246: The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?) 

嘗試3:(每@ DarkFalcon的建議)

Type t = prop.GetType(); 
foreach (var item in prop as ICollection) 
{ 
     //do more cool stuff here 
} 

其中產量:中prop.GetType()

Compiler Error Message: CS0305: Using the generic type 'System.Collections.Generic.ICollection<T>' requires 1 type arguments 
+0

接口的整個點是你不需要知道底層類型。爲了迭代它,「ICollection」或者「IEnumerable」有什麼問題? –

+0

@DarkFalcon我認爲OP實際上想知道泛型類型參數,而不是ICollection的實際實現。 – Tim

+0

也許,但這不是他正在看或改變他的示例代碼... –

回答

1
foreach (var item in prop as System.Collections.IEnumerable) 
{ 

} 

,應該工作。我想,你要通過在你的代碼文件using System.Collections.Generic;(所以它認爲你想System.Collections.Generic.IEnumerable<T>代替System.Collections.IEnumerable

絆倒了。如果你去看看the documentation for foreach你在上面看到:

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T>

所以基本上你只需要讓你的prop被引用爲這兩種類型之一。既然你不知道T,那麼你應該使用非通用的。

1

編譯時類型將始終是一個對象..如果您確定所使用的類型,則可以使用dynamic類型代替

dynamic proplist=prop; 
foreach (dynamic item in proplist) 
{ 
    item.method1(); 
    item.method2(); 
    item.method3(); 
} 
+0

嘿@Anirudh我只是試過了,得到了這個:'''編譯器錯誤消息:CS1579:foreach語句不能在'object'類型的變量上操作,因爲'object'不包含'GetEnumerator'的公共定義' – TechplexEngineer

+0

@TechplexEngineer希望編輯幫助 – Anirudha

+0

雖然這確實起作用,但在變量上丟失智能感知真的很糟糕。 – TechplexEngineer

2

你必須做這樣的:

foreach (var item in prop as System.Collections.IEnumerable) 
{ 
    var t1 = item as Type1; 
    if(t1 != null) 
    { 
     //Do something 
    } 
    var t2 = item as DateTime?; 
    if(t2.HasValue) 
    { 
     //Do your stuff 
    } 
} 
+0

他們看起來像個好主意但我得到這個錯誤:'''編譯器錯誤信息:CS0305:使用泛型類型'System.Collections.Generic .IEnumerable 'requires 1 type arguments''' – TechplexEngineer

+0

Use System.Collections.Enumerable not System.Collections.Generics.Enumerable – Swift