如何獲取通用對象的屬性列表?使用typeof作爲通用對象C#
例如:
object OType;
OType = List<Category>;
foreach (System.Reflection.PropertyInfo prop in typeof(OType).GetProperties())
{
Response.Write(prop.Name + "<BR>")
}
感謝
如何獲取通用對象的屬性列表?使用typeof作爲通用對象C#
例如:
object OType;
OType = List<Category>;
foreach (System.Reflection.PropertyInfo prop in typeof(OType).GetProperties())
{
Response.Write(prop.Name + "<BR>")
}
感謝
爲什麼不使用typeof
與非泛型類型?或者可以在運行時分配OType
。
Type OType = typeof(List<Category>);
foreach (System.Reflection.PropertyInfo prop in OType.GetProperties())
{
Response.Write(prop.Name + "<BR>")
}
我正在使用這個功能:L –
如果我理解正確的話,這個例子是對你的情況的簡化。
如果是這種情況,請考慮使用仿製藥。
public void WriteProps<T>()
{
foreach (System.Reflection.PropertyInfo prop in typeof(T).GetProperties())
{
Response.Write(prop.Name + "<BR>")
}
}
...
WriteProps<List<Category>>();
旁註:
在你的榜樣,你都呈現類型List<Category>
。 GetProperties()
會給你the properties of List。如果你想分類屬性檢查這個SO question。
這聽起來像你實際上想要做的是獲取運行時對象的屬性,而不知道它在編譯時的確切類型。
而不是使用typeof
(這是一個編譯時間常數,基本上)的,使用GetType
:
void PrintOutProperties(object OType)
{
foreach (System.Reflection.PropertyInfo prop in OType.GetType().GetProperties())
{
Response.Write(prop.Name + "<BR>")
}
}
當然,這僅僅在進行OType
不爲空 - 確保包含任何必要的檢查等
如果我事先知道類型,那麼這將起作用,我遇到的問題是一個類型將在這裏傳遞,我想要獲得任何類型的屬性(OType)將被分配給。 –
「任何類型的屬性(OType)將被分配給」 - 這是什麼意思?看起來像一個無限的集合。 –