2015-06-22 42 views
2

如何获取通用对象的属性列表?使用typeof作为通用对象C#

例如:

object OType; 
OType = List<Category>; 
foreach (System.Reflection.PropertyInfo prop in typeof(OType).GetProperties()) 
{ 
    Response.Write(prop.Name + "<BR>") 
} 

感谢

+0

如果我事先知道类型,那么这将起作用,我遇到的问题是一个类型将在这里传递,我想要获得任何类型的属性(OType)将被分配给。 –

+0

“任何类型的属性(OType)将被分配给” - 这是什么意思?看起来像一个无限的集合。 –

回答

0

为什么不使用typeof与非泛型类型?或者可以在运行时分配OType

Type OType = typeof(List<Category>); 
foreach (System.Reflection.PropertyInfo prop in OType.GetProperties()) 
{ 
    Response.Write(prop.Name + "<BR>") 
} 
+0

我正在使用这个功能:L –

3

如果我理解正确的话,这个例子是对你的情况的简化。

如果是这种情况,请考虑使用仿制药

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

1

这听起来像你实际上想要做的是获取运行时对象的属性,而不知道它在编译时的确切类型。

而不是使用typeof(这是一个编译时间常数,基本上)的,使用GetType

void PrintOutProperties(object OType) 
{ 
    foreach (System.Reflection.PropertyInfo prop in OType.GetType().GetProperties()) 
    { 
     Response.Write(prop.Name + "<BR>") 
    } 
} 

当然,这仅仅在进行OType不为空 - 确保包含任何必要的检查等