[英]C# object runtime type casting
我有一個變量(我稱它為prop),其類型為“對象”,我知道基礎類型將始終是某種ICollection。 我想迭代這個集合並串起所有元素。
我的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
}
產生:
Compiler Error Message: CS0305: Using the generic type 'System.Collections.Generic.ICollection<T>' requires 1 type arguments
您必須這樣做:
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
}
}
prop.GetType()
編譯時類型將始終是一個對象。如果您確定所使用的類型,則可以使用dynamic
類型來代替
dynamic proplist=prop;
foreach (dynamic item in proplist)
{
item.method1();
item.method2();
item.method3();
}
foreach (var item in prop as System.Collections.IEnumerable)
{
}
那應該工作。 我認為using System.Collections.Generic;
您陷入using System.Collections.Generic;
在代碼文件中(因此認為您需要System.Collections.Generic.IEnumerable<T>
而不是System.Collections.IEnumerable
)
如果您查看foreach
的文檔,則會在頂部看到以下內容:
foreach語句對實現
System.Collections.IEnumerable
或System.Collections.Generic.IEnumerable<T>
的數組或對象集合中的每個元素重復一組嵌入式語句。
因此,基本上,您只需prop
自己的prop
被引用為這兩種類型之一即可。 由於您不知道T,因此您應該使用非通用T。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.