2012-11-28 53 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;指令。

相关问题