C# 获取类中属性的最高值
我想在班上获得最多的财产:C# 获取类中属性的最高值,c#,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 _
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();
}
}
公共类aClass
{
公共int-PropA{get;set;}=1;
公共int-PropB{get;set;}=18;
公共int-PropC{get;set;}=25;
public int GetMaxConfiguratableColumns()
{
返回新列表{this.PropA,this.PropB,this.PropC}.Max();
}
}
使用\u 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;
}
无论谁需要它。它必须使用反射吗?或者可以接受不同的方法?您所说的最高数量的房产是什么意思?
\u Info
包含什么?的可能重复项。另外,如果使用字典
,而不是静态编码属性,则可以计算键数。我正在尝试获取数字25(最高属性)