2015-11-06 62 views
0

說我有像如何在類中創建並初始化一個靜態只讀數組struct?

public struct pair{ float x,y;} 

我想創建對一個恆定的查找陣列的一類,其也固定數目的內部的結構體。 喜歡的東西

public class MyClass{ 
    static readonly fixed pair[7] _lookup; 
} 

我不知道如何申報,也沒有對其進行初始化(我在哪裏設置每個值是多少?)。

+0

你能解釋一下你的意思:_how申報,也沒有初始化it_ ? – Grundy

+0

我不知道正確的語法,我不知道如何用我想要的值初始化它。 – Icebone1000

+0

你可以從[guide](https://msdn.microsoft.com/en-us/library/0taef578.aspx) – Grundy

回答

2

使用使用類相似的結構,這樣你就可以定義

public struct Pair {public float x, y;} 

public class MyClass 
{ 
    public static readonly Pair[] _lookup = new Pair[]{ 
     new Pair(){x=1, y=2}, 
     new Pair(){x=1, y=2}, 
     new Pair(){x=1, y=2}, 
     new Pair(){x=1, y=2}, 
     new Pair(){x=1, y=2}, 
     new Pair(){x=1, y=2}, 
     new Pair(){x=1, y=2} 
    }; 
} 
2

指定值時,也可以使用靜態構造函數

public struct pair 
{ 
    float x, y; 

    public pair(float x, float y) 
    { 
     this.x = x; 
     this.y = y; 
    } 
} 

public class MyClass 
{ 
    public static readonly pair[] lookup; 

    static MyClass() 
    { 
     lookup = new pair[7] { new pair(1, 2), new pair(2, 3), new pair(3, 4), new pair(4, 5), new pair(5, 6), new pair(6, 7), new pair(7, 8) }; 
    } 
}