简体   繁体   中英

How to create and initialize a static readonly array of struct, inside a class?

Say I have a struct like

public struct pair{ float x,y;}

I want to create a constant lookup array of pairs inside a class, its also fixed number. Something like

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

I dont know how to declare nor initialize it(where do I set the values for each one?).

You can also use a static constructor

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

Using structures similar using classes, so you can assign value on definition

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM