[英]Using typeof for a generic object C#
如何獲得通用對象的屬性列表?
例如:
object OType;
OType = List<Category>;
foreach (System.Reflection.PropertyInfo prop in typeof(OType).GetProperties())
{
Response.Write(prop.Name + "<BR>")
}
謝謝
如果我理解正確,那么該示例就是您的案例的簡化。
如果是這種情況,請考慮使用泛型 。
public void WriteProps<T>()
{
foreach (System.Reflection.PropertyInfo prop in typeof(T).GetProperties())
{
Response.Write(prop.Name + "<BR>")
}
}
...
WriteProps<List<Category>>();
邊注:
在您的示例中,您顯示的是List<Category>
。 GetProperties()
將為您提供List的屬性 。 如果要分類屬性,請檢查此SO問題 。
聽起來您實際上想要做的是獲取運行時對象的屬性,而在編譯時不知道其確切類型。
代替使用typeof
(基本上是一個編譯時常量),請使用GetType
:
void PrintOutProperties(object OType)
{
foreach (System.Reflection.PropertyInfo prop in OType.GetType().GetProperties())
{
Response.Write(prop.Name + "<BR>")
}
}
當然,這僅在OType
不為null時有效-確保包括任何必要的檢查等。
為什么不將typeof
與非泛型類型一起使用? 或可以在運行時分配OType
。
Type OType = typeof(List<Category>);
foreach (System.Reflection.PropertyInfo prop in OType.GetProperties())
{
Response.Write(prop.Name + "<BR>")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.