簡體   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();
        
    }
}

它與ToString()方法有關,因為我想動態獲取所有道具名稱及其值。 我不知道是否可以在當前的 class 內部執行此操作。

這不是問題, this可以在此處刪除:

var allProperties = GetType().GetProperties();

並將this object 設置為prop.GetValue(object? obj)的參數。

整個代碼如下所示:

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();
}

可以在這里看到一個例子:

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();
    }
}

你可以像這樣運行上面的代碼:

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