主程序:
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
方法。 - gdoronToString
返回所有属性值。相反,如果需要,您可以提供一个名为GetPropertyInfo
的方法来实现此功能。 - Tim Schmelter