【发布时间】:2012-02-15 18:40:40
【问题描述】:
我通常重写 ToString() 方法以输出属性名称和与它们关联的值。我有点厌倦了手工写这些,所以我正在寻找一个动态的解决方案。
主要:
TestingClass tc = new TestingClass()
{
Prop1 = "blah1",
Prop2 = "blah2"
};
Console.WriteLine(tc.ToString());
Console.ReadLine();
测试类:
public class TestingClass
{
public string Prop1 { get; set; }//properties
public string Prop2 { get; set; }
public void Method1(string a) { }//method
public TestingClass() { }//const
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (Type type in System.Reflection.Assembly.GetExecutingAssembly().GetTypes())
{
foreach (System.Reflection.PropertyInfo property in type.GetProperties())
{
sb.Append(property.Name);
sb.Append(": ");
sb.Append(this.GetType().GetProperty(property.Name).Name);
sb.Append(System.Environment.NewLine);
}
}
return sb.ToString();
}
}
当前输出:
Prop1: System.String Prop1
Prop2: System.String Prop2
期望的输出:
Prop1: blah1
Prop2: blah2
我对其他解决方案持开放态度,它不必使用反射,它只需要产生所需的输出。
【问题讨论】:
-
你需要使用
GetValue方法。 -
一般情况下,您不应使用
ToString返回所有属性值。相反,您可以提供一个方法GetPropertyInfo,如果您愿意的话。
标签: c# reflection overriding tostring