2012-11-28 54 views
0

我有一個包含Int32類型的多個屬性的類:有沒有更好的方法來總結多個屬性?

public class MyClass 
{ 
    public int C1 { get; set; } 
    public int C2 { get; set; } 
    public int C3 { get; set; } 
    . 
    . 
    . 
    public int Cn { get; set; } 
} 

我要總結這一切特性。而不是:

int sum = C1 + C2 + C3 + ... + Cn 

有沒有更高效/優雅的方法?

+1

不,這就是它 – leppie

+6

爲什麼不使用這些屬性的數組或列表? –

+3

反射並不優雅,效率更低。 –

回答

2

你可以假,但我不知道它是多麼有用:

using System; 
using System.Collections.Generic; 
using System.Linq; 

namespace Demo 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var test = new MyClass(); 
      // ... 
      int sum = test.All().Sum(); 
     } 
    } 

    public class MyClass 
    { 
     public int C1 { get; set; } 
     public int C2 { get; set; } 
     public int C3 { get; set; } 
     // ... 
     public int Cn { get; set; } 

     public IEnumerable<int> All() 
     { 
      yield return C1; 
      yield return C2; 
      yield return C3; 
      // ... 
      yield return Cn; 
     } 
    } 
}                        
1

也許您可以使用具有IEnumarable接口與自定義類的數組或數據結構。然後你可以使用linq來做Sum()。

+0

我知道。我的問題與這個特例有關。 – Sergiu

+0

然後你必須看看反射,但它不是'優雅或高效'。對你的課進行Sum操作的擴展方法。 – Peter

1

如果有足夠強的需求將值存儲在單獨的成員(屬性,字段)中,那麼是的,這是唯一的方法。如果您有一個數字列表,請將它們存儲在一個列表中,而不是單獨的成員中。

或者醜:

new[]{C1,C2,C3,C4}.Sum() 

但更多的字符比單一的 「+」 反正。現在

1
public class MyClass 
{ 
    readonly int[] _cs = new int[n]; 

    public int[] Cs { get { return _cs; } } 

    public int C1 { get { return Cs[0]; } set { Cs[0] = value; } } 
    public int C2 { get { return Cs[1]; } set { Cs[1] = value; } } 
    public int C3 { get { return Cs[2]; } set { Cs[2] = value; } } 
    . 
    . 
    . 
    public int Cn { get { return Cs[n-1]; } set { Cs[n-1] = value; } } 
} 

可以使用Enumerable.SumMyClass.Cs,你仍然可以映射C1C2,...到數據庫字段。

2

如果你真的想,而不必鍵入每次可以使用反射來遍歷執行財產的總和你的財產,但這涉及很大的性能成本。然而,爲了好玩,你可以做這樣的事情:

var item = new MyClass(); 
// Populate the values somehow 
var result = item.GetType().GetProperties() 
    .Where(pi => pi.PropertyType == typeof(Int32)) 
    .Select(pi => Convert.ToInt32(pi.GetValue(item, null))) 
    .Sum(); 

PS:不要忘了添加using System.Reflection;指令。

相關問題