对泛型对象C#使用typeof

本文关键字:使用 typeof 对象 泛型 | 更新日期: 2023-09-27 17:59:07

如何获取泛型对象的属性列表?

例如:

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

感谢

对泛型对象C#使用typeof

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

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

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不为空时,这才有效-确保包括任何必要的检查等。

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

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