我想转换一下:
class ObjectWithArray
{
int iSomeValue;
SubObject[] arrSubs;
}
ObjectWithArray objWithArr;
到此:
class ObjectWithoutArray
{
int iSomeValue;
SubObject sub;
}
ObjectWithoutArray[] objNoArr;
其中每个objNoArr将具有与objWithArr相同的iSomeValue,但是objWithArr.arrSubs中的单个SubObject;
首先想到的是简单地循环遍历objWithArr.arrSubs并使用当前的SubObject创建一个新的ObjectWithoutArray并将该新对象添加到数组中。但是,我想知道现有框架中是否有任何功能可以做到这一点?
另外,如何简单地将ObjectWithArray objWithArr分解为ObjectWithArray [] arrObjWithArr,其中每个arrObjectWithArr.arrSubs只包含原始objWithArr中的一个SubObject?
答案 0 :(得分: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;
}
}
答案 1 :(得分: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;
}
}