C# 对传入的对象属性进行迭代的方法
试图弄清楚如何创建一个方法,该方法将迭代对象的属性,并输出它们(现在说console.writeline) 这是否可能使用反射 e、 g 试试下面的方法C# 对传入的对象属性进行迭代的方法,c#,oop,reflection,C#,Oop,Reflection,试图弄清楚如何创建一个方法,该方法将迭代对象的属性,并输出它们(现在说console.writeline) 这是否可能使用反射 e、 g 试试下面的方法 public void OutputProperties(object o) { if ( o == null ) { throw new ArgumentNullException(); } foreach ( var prop in o.GetType().GetProperties(BindingFlags.Public | Bi
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);
}
}
这将输出在特定类型上声明的所有属性。如果任何属性在求值时抛出异常,它将失败。是,您可以使用
foreach (var objProperty in o.GetType().GetProperties())
{
Console.WriteLine(objProperty.Name + ": " + objProperty.GetValue(o, null));
}
另一种方法是使用
TypeDescriptor
,允许自定义对象模型在运行时显示灵活的属性(即,您看到的不仅仅是类上的内容,还可以使用自定义类型转换器进行字符串转换):
请注意,反射是默认的实现-但是许多其他更有趣的模型是可能的,通过
ICustomTypeDescriptor
和TypeDescriptionProvider
它们在内部不使用反射吗?
foreach (var objProperty in o.GetType().GetProperties())
{
Console.WriteLine(objProperty.Name + ": " + objProperty.GetValue(o, null));
}
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);
}
}