简体   繁体   English

如何获取 class 中所有属性的值

[英]How to get values of all properties inside a class

public class SumsThirdDegree : ThirdDegree
{
    public SumsThirdDegree(List<ThirdDegree> allValues)
    {
        this.SumAllValues(allValues);
    }

    private void SumAllValues(List<ThirdDegree> allValues) 
    {
        this.X = allValues.Sum(x => x.X);
        this.Y = allValues.Sum(x => x.Y);
        this.XY = allValues.Sum(x => x.XY);
        this.XSecY = allValues.Sum(x => x.XSecY);
        this.XThirdY = allValues.Sum(x => x.XThirdY);
        this.XSecond = allValues.Sum(x => x.XSecond);
        this.XThird = allValues.Sum(x => x.XThird);
        this.XFourth = allValues.Sum(x => x.XFourth);
        this.XFifth = allValues.Sum(x => x.XFifth);
        this.XSixth = allValues.Sum(x => x.XSixth);
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        
        var allProperties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var prop in allProperties)
        {
            sb.AppendLine($"Sum of {prop.Name} is: {prop.GetValue()}");
        }

        return sb.ToString();
        
    }
}

It is about ToString() method because I want to dynamically get all props names and their values.它与ToString()方法有关,因为我想动态获取所有道具名称及其值。 I don't know if it is possible to do that inside of the current class.我不知道是否可以在当前的 class 内部执行此操作。

It is not issue, however this can be removed here:这不是问题, this可以在此处删除:

var allProperties = GetType().GetProperties();

And set this object as parameter for prop.GetValue(object? obj) .并将this object 设置为prop.GetValue(object? obj)的参数。

The whole code would look like this:整个代码如下所示:

public override string ToString()
{
    StringBuilder sb = new StringBuilder();

    var allProperties = GetType().GetProperties();

    foreach (var prop in allProperties)
    {
        sb.AppendLine($"Sum of {prop.Name} is: {prop.GetValue(this)}");
    }

    return sb.ToString();
}

An example can be seen here:可以在这里看到一个例子:

class A
{
    public int Foo { get; set; }
}

class B : A
{
    public string Bar { get; set; }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();

        var allProperties = GetType().GetProperties();

        foreach (var prop in allProperties)
        {
            sb.AppendLine($"Sum of {prop.Name} is: {prop.GetValue(this)}");
        }

        return sb.ToString();
    }
}

and you can run the above code like this:你可以像这样运行上面的代码:

B c = new B() { Foo = 1, Bar = "2" };
string str = c.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM