如何访问未知类型的对象属性名称

时间:2011-03-28 14:45:15

标签: c# asp.net reflection

我使用的函数包含 object 类型参数。我想获得这个未知类型对象的属性的名称。我怎么能这样做?

KR,

Dakmaz

3 个答案:

答案 0 :(得分:4)

使用GetProperties

var properties = obj.GetType().GetProperties();

答案 1 :(得分:2)

请勿使用object类型的参数,而是使用generics

然后,您可以constrain此通用实现接口或从基类继承。

然后,您将能够访问受约束的接口/基本类型中定义的属性和功能。您还可以定义自己的界面并限制它。

示例代码:

public void MyFunc<T>(T myParam)
   where T : IEnumerable // or some other interface or base class.
{
   foreach (var child in myParam) // uses the interface IEnumerable that the generic was constrained to
   {
      // do something
   }
}

答案 2 :(得分:0)

http://www.csharp-examples.net/reflection-property-names/

  

我使用包含对象的函数

我闻到了糟糕的代码设计。