2015-11-06 63 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) }; 
    } 
}