想象一下有很多公共财产的班级.出于某种原因,不可能将此类重构为较小的子类.
我想添加一个ToString覆盖,返回以下内容:
Property 1: Value of property 1\n Property 2: Value of property 2\n ...
有没有办法做到这一点?
我通常覆盖ToString()方法以输出属性名称和与之关联的值.我有点厌倦了手工编写这些,所以我正在寻找一个动态的解决方案.
主要:
TestingClass tc = new TestingClass()
{
Prop1 = "blah1",
Prop2 = "blah2"
};
Console.WriteLine(tc.ToString());
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
TestingClass:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
目前输出: …