2011-03-28 90 views
1

我使用的函数包含对象类型参数。我想获取这个未知类型对象的属性的名称。我怎样才能做到这一点?如何访问未知类型对象的属性名称

KR,

Dakmaz

+0

见思考 - http://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx – Mitul 2011-03-28 14:49:51

回答

4

使用GetProperties

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

请勿使用对象类型的参数,而应使用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 
    } 
}