2009-10-06 80 views
2

试图弄清楚如何创建一个方法来迭代对象的属性,并输出它们(比如现在称为console.writeline)。一种迭代传入的对象属性的方法

这可能使用反射吗?

例如

public void OutputProperties(object o) 
{ 

     // loop through all properties and output the values 

} 

回答

4

请尝试以下

public void OutputProperties(object o) { 
    if (o == null) { throw new ArgumentNullException(); } 
    foreach (var prop in o.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { 
    var value = prop.GetValue(o,null); 
    Console.WriteLine("{0}={1}", prop.Name, value); 
    } 
} 

这将输出的具体类型声明的所有属性。如果任何属性在评估时抛出异常,它将会失败。

1

是的,你可以使用

foreach (var objProperty in o.GetType().GetProperties()) 
{ 
    Console.WriteLine(objProperty.Name + ": " + objProperty.GetValue(o, null)); 
} 
2

使用TypeDescriptor,允许自定义对象模型的替代方法在运行时显示灵活特性(即你所看到的可不仅仅是什么是在类的更多,并且可以使用自定义类型转换器做字符串转换):

public static void OutputProperties(object obj) 
{ 
    if (obj == null) throw new ArgumentNullException("obj"); 
    foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) 
    { 
     object val = prop.GetValue(obj); 
     string s = prop.Converter.ConvertToString(val); 
     Console.WriteLine(prop.Name + ": " + s); 
    } 
} 

注意,反射是默认实现 - 但许多其他更有趣的模式是可能的,通过ICustomTypeDescriptorTypeDescriptionProvider

+0

内部是不是他们使用反射? – mrblah 2009-10-06 23:46:23