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

  • 本文关键字:属性 何获取 获取 c# oop
  • 更新时间 :
  • 英文 :

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()方法的,因为我想动态地获取所有道具的名称及其值。我不知道是否有可能在当前类中这样做。

这不是问题,但是this可以在这里删除:

var allProperties = GetType().GetProperties();

并将this对象设置为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();

最新更新