【问题标题】:How do I automatically display all properties of a class, which is a property in another class?如何自动显示一个类的所有属性,这是另一个类的属性?
【发布时间】:2020-04-30 12:19:41
【问题描述】:

我想打印我班级的所有值,类似于this 问题。不同之处在于我的班级是另一个班级的财产。我尝试了以下简单的代码:

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 总是无效的,所以他跳过了整个循环。我做错了什么?

【问题讨论】:

    标签: c# class properties subclassing


    【解决方案1】:

    ClassA 没有属性,只有字段。

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

    _PropertyInfos 不是null,它是空的。

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

    【讨论】:

      猜你喜欢
      • 2022-12-19
      • 2020-09-01
      • 2017-01-16
      • 1970-01-01
      • 2020-03-05
      • 2014-06-07
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多