0

どこかからクラス AAA のオブジェクトを取得しており、そのオブジェクトにさらに情報を追加したいと考えています。そこで、AAA から派生した新しいクラス BBB を作成しています。クラス BBB には、追加のフィールド ディクショナリがあります。このディクショナリは、クラス AAA オブジェクトと、ディクショナリのキーとして使用したい項目の配列を取得する派生クラス コンストラクターで生成されます。このディクショナリーの値は、クラス AAA のオブジェクトのフィールドの要素です。打撃のサンプルコードで同様のシナリオを作成しようとしました:

void Main(){    
     A obj = new A () ;
     obj.prop1 =  new int [] {5 ,10, 15}   ;
     obj.prop2 =  "Hello" ;
     obj.prop3 = "World" ;
//   obj.Dump () ;
     B obj2 = new B (new int [] {1,2,3}, obj)  ;     
//   obj2.Dump () ;

}

// Define other methods and classes here
public class A {
    public int [] prop1 ;
    public string prop2 ;
    public string prop3 ;
}

public class B : A {
    public Dictionary <int, int> prop4 ;
    public B (int [] keys, A a) {
    prop4 = new Dictionary <int, int> () ;
        if (keys.Length == a.prop1.Length ) {
            for (int i = 0 ; i < keys.Length ; i++ ) {
                prop4.Add (keys[i], a.prop1[i]) ;
            }
            // is there a way to obsolete below lines of code???
            this.prop1 = a.prop1 ; 
            this.prop2 = a.prop2 ;
            this.prop3 = a.prop3 ;
        }
        else {
            throw new Exception ("something wrong") ;
        }           
    }
}

派生クラスのコンストラクターで、プロパティを手動で入力していますが、そうしたくありません。それを行う別の方法はありますか。実際のクラスには 20 を超えるプロパティがあります。

4

5 に答える 5

2

あなたが求めていることはできませんが、クラスのコピーコンストラクターを作成し、Aそれをクラスコンストラクターで使用することをお勧めしますB:

// Define other methods and classes here
public class A
{
    public int[] prop1;
    public string prop2;
    public string prop3;

    public A()
    {
    }

    public A(A orig)
    {
        prop1 = orig.prop1;
        prop2 = orig.prop2;
        prop3 = orig.prop3;
    }
}

public class B : A
{
    public Dictionary<int, int> prop4;

    public B(int[] keys, A a) : base( a )
    {
        prop4 = new Dictionary<int, int>();

        if (keys.Length == prop1.Length)
        {
            for (int i = 0; i < keys.Length; i++)
            {
                prop4.Add(keys[i], prop1[i]);
            }
        }
        else
        {
            throw new Exception("something wrong");
        }
    }
}
于 2013-10-22T15:05:30.380 に答える
0

配列を定義します。次に、配列内のアイテムを個々のプロパティにキャストします

クラスAで

public object[] properties;

public int[] prop1 {
  get { return (int[]) properties[0]; }
  set { properties[0] = value; } }

public string prop2 {
  get { return (string)properties[1];  }
  set { properties[1] = value ; } }

B のコンストラクター

public B (int[] keys, A obj)
    {
        properties = A.properties;
    }
于 2013-10-22T15:12:03.107 に答える