如何自动显示 class 的所有属性,这是另一个 class 中的 属性?

How do I automatically display all properties of a class, which is a property in another class?

我想打印 class 的所有值,类似于 this 问题。不同的是,我的 class 是另一个 class 中的 属性。我尝试了以下简单代码:

public class ClassA
{
    public double PropA = 5;
    private PropertyInfo[] _PropertyInfos = null;
    public void Print()
    {
        if (_PropertyInfos == null)
            _PropertyInfos = this.GetType().GetProperties();

        foreach (var info in _PropertyInfos)
        {
            Console.WriteLine(info.Name + ": " + info.GetValue(this).ToString());
        }
    }
}

public class ClassB
{
    public ClassA PropB = new ClassA();
}

class Program
{
    static void Main(string[] args)
    {
        ClassB classB = new ClassB();

        classB.PropB.Print();
    }
}

由于某种原因_PropertyInfos 总是无效的,所以他跳过了整个循环。我做错了什么?

ClassA 没有属性,只有字段。

public double PropA = 5;          // Field
public double PropA { get; set; } // Property

_PropertyInfos 不是 null,它是空的。

要么将您的字段转换为属性,要么开始使用 this.GetType().GetFields() 交换 PropertyInfo[]FieldInfo[]