使用typeof作为通用对象C#

时间:2015-06-22 08:44:35

标签: c# typeof

如何获取通用对象的属性列表?

例如:

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

由于

3 个答案:

答案 0 :(得分:3)

如果我理解正确,这个例子就是你案例的简化。

如果是这种情况,请考虑使用泛型

return tryAdvance((int i)->c.accept(i));

旁注:

在您的示例中,您显示的是public void WriteProps<T>() { foreach (System.Reflection.PropertyInfo prop in typeof(T).GetProperties()) { Response.Write(prop.Name + "<BR>") } } ... WriteProps<List<Category>>(); 类型。 List<Category>将为您the properties of List。如果您想要“类别”属性,请选中此SO question

答案 1 :(得分:1)

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

不使用typeof(基本上是编译时常量),而是使用GetType

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

当然,这仅在OType不为空时才有效 - 确保包括任何必要的检查等。

答案 2 :(得分:0)

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

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