2017-02-27 54 views
0

我正在用C#編程一個遊戲,我正在使用SoA模式來處理性能關鍵組件。C#中的數組結構 - 減少樣板代碼寫作

下面是一個例子:

public class ComponentData 
{ 
    public int[] Ints; 
    public float[] Floats; 
} 

理想情況下,我想其他的程序員才應指定該數據(如上),並用它做。然而,有些操作必須完成每個陣列,像分配,複製,成長等現在我使用的是抽象方法的抽象類來實現的,就像這樣:

public class ComponentData : BaseData 
{ 
    public int[] Ints; 
    public float[] Floats; 

    protected override void Allocate(int size) 
    { 
     Ints = new int[size]; 
     Floats = new float[size]; 
    } 

    protected override void Copy(int source, int destination) 
    { 
     Ints[destination] = Ints[source]; 
     Floats[destination] = Floats[source]; 
    } 

    // And so on... 
} 

這就要求程序員在每次編寫新組件時添加所有這些樣板代碼,並且每次添加一個新數組。

我試圖通過使用模板計算出來,雖然這適用於AoS模式,但它對SoA沒有太大的好處(因爲Data : BaseData<int, float>會非常模糊)。

所以我想聽聽有關將這些數組自動「注入」到某處的想法,以減少大量的樣板代碼。

回答

0

我建議定義一個由類使用的所有數組的集合,然後在循環中對它們全部進行所有必要的操作。

+0

不確定我關注。難道這不會是至少相同數量的代碼寫嗎? – jesta

1

當時的想法是以下幾點:

public abstract class ComponentData : BaseData 
{ 
    public Collection<Array> ArraysRegister { get; private set; } 

    public int[] Ints; 

    public float[] Floats; 

    public ComponentData() 
    { 
     ArraysRegister = new Collection<Array>(); 
     ArraysRegister.Add(this.Ints); 
     ArraysRegister.Add(this.Floats); 
     /* whatever you need in base class*/ 
    } 

    protected void Copy(int source, int destination) 
    { 
     for (int i = 0; i < ArraysRegister.Count; i++) 
     { 
     ArraysRegister[i][destination] = ArraysRegister[i][source]; 
     } 
    } 
    /* All the other methods */ 
} 

public class SomeComponentData : ComponentData 
{ 
    // In child class you only have to define property... 
    public decimal[] Decimals; 

    public SomeComponentData() 
    { 
     // ... and add it to Register 
     ArraysRegister.Add(this.Decimals); 
    } 
    // And no need to modify all the base methods 
} 

這是不完美但(東西必須與分配做),但至少落實兒童類,你不必重寫基地的所有方法處理數組的類。值得做還是取決於你有多少類似的方法。

+0

我明白了。這其實非常好!將解決複製粘貼一切的大部分痛苦。謝謝! – jesta

+0

樂意幫忙) – Aleksei