获取类中属性的最高值

  • 本文关键字:最高值 属性 获取 c#
  • 更新时间 :
  • 英文 :


我正在尝试获得类中所有同类中数量最多的:

public class aClass{ 
public int PropA{ get; set; } = 1;
public int PropB{ get; set; } = 18;
public int PropC{ get; set; } = 25; 
}  

这是我的代码:

public int GetMaxConfiguratableColumns()
{
int _HighestNumber = 0;
PropertyInfo[] _Info = this.GetType().GetProperties(); 
foreach(PropertyInfo _PropretyInfo in _Info)
{
//I'm lost here!!!!!!!
}
return _HighestNumber;
}

有什么建议吗?谢谢!

如果它不必使用反射,我可以建议这样的东西吗?

public class aClass
{
public int PropA { get; set; } = 1;
public int PropB { get; set; } = 18;
public int PropC { get; set; } = 25;
public int GetMaxConfiguratableColumns()
{
return new List<int> {this.PropA, this.PropB, this.PropC}.Max();
}
}

使用_PropretyInfo.GetValue(myObject)获取当前属性的值,然后将其存储在 temp 变量中,然后迭代并将 temp 值与其余值进行比较

我想你最终会得到这样的东西:

int highestNumber = 0;      
PropertyInfo[] info = this.GetType().GetProperties(); 
foreach(PropertyInfo propInfo in info)
{
if (propInfo.PropertyType == typeof(int))
{
int propValue = (int)(propInfo.GetValue(this, null));
if (propValue > highestNumber) {
highestNumber = propValue;
}
}
}
return highestNumber;

得到我的答案:

public int GetMaxConfiguratableColumns()
{
PaymentHeader PaymentHeader = new PaymentHeader();
int max = typeof(PaymentHeader)
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
.Select(x => (int)x.GetValue(PaymentHeader)).Max();
return max;
} 

给任何需要这个的人。

最新更新