2017-07-20 14 views
-2

のプロパティの最大値を取得します。私は私のクラスのすべてのpropretiesの最大数を取得しようとしているクラス

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

任意の提案?ありがとう!

+0

反射を使用する必要がありますか?異なるアプローチが受け入れられるだろうか? –

+0

最高のプロパティ数はどういう意味ですか? '_Info'には何が入っていますか? – FortyTwo

+4

[C#のリフレクションを使用して文字列からプロパティ値を取得](https://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp)の重複が考えられます。また[Reflectionを使用してプロパティ値を取得する方法](https://stackoverflow.com/questions/10338018/how-to-get-a-property-value-using-reflection)。 – hatchet

答えて

1

リフレクションを使用する必要がない場合は、このようなことを提案できますか?

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

その後、一時変数に格納し、私はあなたがこのような何かをする羽目になるだろうと思う残り

0

で一時値を反復して比較し、あなたの現在のプロパティの値を取得するために使用_PropretyInfo.GetValue(myObject)

これを必要とする誰に

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

 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; 
0

は私の答えを得ました。

関連する問題