1

これを変換したい:

class ObjectWithArray
{
    int iSomeValue;
    SubObject[] arrSubs;
}

ObjectWithArray objWithArr;

これに:

class ObjectWithoutArray
{
    int iSomeValue;
    SubObject sub;
}

ObjectWithoutArray[] objNoArr;

各 objNoArr は、objWithArr が持っていたのと同じ iSomeValue を持ちますが、objWithArr.arrSubs にあった単一のサブオブジェクトを持ちます。

頭に浮かぶ最初のアイデアは、単純に objWithArr.arrSubs をループし、現在の SubObject を使用して新しい ObjectWithoutArray を作成し、その新しいオブジェクトを配列に追加することです。しかし、既存のフレームワークにこれを行う機能があるかどうか疑問に思っていますか?


また、ObjectWithArray objWithArr を単純に ObjectWithArray[] arrObjWithArr に分割して、各 arrObjectWithArr.arrSubs に元の objWithArr のサブオブジェクトを 1 つだけ含めるのはどうですか?

4

2 に答える 2

2

このようなものはおそらくうまくいくでしょう。

class ObjectWithArray
{
    int iSomeValue;
    SubObject[] arrSubs;

    ObjectWithArray(){} //whatever you do for constructor


    public ObjectWithoutArray[] toNoArray(){
        ObjectWithoutArray[] retVal = new ObjectWithoutArray[arrSubs.length];

        for(int i = 0; i < arrSubs.length;  i++){
          retVal[i] = new ObjectWithoutArray(this.iSomeValue, arrSubs[i]);
        }

       return retVal;
    }
}

class ObjectWithoutArray
{
    int iSomeValue;
    SubObject sub;

    public ObjectWithoutArray(int iSomeValue, SubObject sub){
       this.iSomeValue = iSomeValue;
       this.sub = sub;
    }
}
于 2012-10-26T23:06:46.167 に答える
0

Linqを使用すると、非常に簡単に実行できます。

class ObjectWithArray
{
    int iSomeValue;
    SubObject[] arrSubs;

    ObjectWithArray() { } //whatever you do for constructor


    public ObjectWithoutArray[] toNoArray()
    {
        ObjectWithoutArray[] retVal = arrSubs.Select(sub => new ObjectWithoutArray(iSomeValue, sub)).ToArray();
        return retVal;
    }
}
于 2012-10-27T00:18:37.653 に答える