【问题标题】:How to create and initialize a static readonly array of struct, inside a class?如何在类中创建和初始化结构的静态只读数组?
【发布时间】:2015-11-06 17:04:19
【问题描述】:

假设我有一个类似的结构

public struct pair{ float x,y;}

我想在一个类中创建一个常量查找数组,它也是固定的数字。 类似的东西

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

我不知道如何声明或初始化它(我在哪里设置每个值?)。

【问题讨论】:

  • 你能解释一下你的意思吗:如何声明或初始化它
  • 我不知道正确的语法,也不知道如何用我想要的值来初始化它。
  • 你可以从guide开始

标签: c# arrays static constants


【解决方案1】:

你也可以使用静态构造函数

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) };
    }
}

【讨论】:

    【解决方案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}
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 2021-01-31
      • 2011-02-08
      • 2014-10-07
      • 2011-01-07
      • 2011-06-04
      • 2013-09-22
      相关资源
      最近更新 更多