相关疑难解决方法(0)

如何在字符串中自动显示类的所有属性及其值?

想象一下有很多公共财产的班级.出于某种原因,不可能将此类重构为较小的子类.

我想添加一个ToString覆盖,返回以下内容:

Property 1: Value of property 1\n
Property 2: Value of property 2\n
...

有没有办法做到这一点?

.net c# properties tostring

34
推荐指数
2
解决办法
4万
查看次数

使用Reflection动态覆盖ToString()

我通常覆盖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)

目前输出: …

c# reflection overriding tostring

10
推荐指数
2
解决办法
8875
查看次数

标签 统计

c# ×2

tostring ×2

.net ×1

overriding ×1

properties ×1

reflection ×1