[英]How to initialize a struct in array with readonly values using Expression Trees in C#
[英]How to create and initialize a static readonly array of struct, inside a class?
说我有一个像
public struct pair{ float x,y;}
我想在一个类中创建一个成对的常量查找数组,它的数量也是固定的。 就像是
public class MyClass{
static readonly fixed pair[7] _lookup;
}
我不知道如何声明或初始化它(我在哪里设置每个值?)。
您还可以使用静态构造函数
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) };
}
}
使用与类相似的结构,因此您可以在定义时分配值
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}
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.