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

より効率的/エレガントな方法はありますか?

4

5 に答える 5

3

あなたはそれを偽造することができますが、それがどれほど役立つかはわかりません:

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; 
        }
    }
}                                                                                            
于 2012-11-28T08:44:47.357 に答える
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();

using System.Reflection;PS:ディレクティブを追加することを忘れないでください。

于 2012-11-28T08:48:14.813 に答える
1

おそらく、IEnumarable インターフェイスとカスタム クラスを持つ配列またはデータ構造を使用できます。次に、linq を使用して Sum() を実行できます。

于 2012-11-28T08:33:48.547 に答える
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.Sumになり、 、、 ... をデータベース フィールドにMyClass.Csマップすることもできます。C1C2

于 2012-11-28T08:41:07.023 に答える
1

値を別々のメンバー (プロパティ、フィールド) に保存する必要性が十分にある場合は、そうです。それが唯一の方法です。ただし、番号のリストがある場合は、それらを個別のメンバーではなく、リストに保存してください。

または、醜い:

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

とにかく、単一の「+」よりも多くの文字。

于 2012-11-28T08:36:42.373 に答える