我有一個變量(我稱之爲道具),其類型是「對象」,我知道底層類型將永遠是某種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
接口的整個點是你不需要知道底層類型。爲了迭代它,「ICollection」或者「IEnumerable」有什麼問題? –
@DarkFalcon我認爲OP實際上想知道泛型類型參數,而不是ICollection的實際實現。 – Tim
也許,但這不是他正在看或改變他的示例代碼... –