C# array within a struct

前端 未结 5 1041
余生分开走
余生分开走 2020-12-01 10:59

Want to do this: (EDIT: bad sample code, ignore and skip below)

struct RECORD {
    char[] name = new char[16];
    int dt1;
}
struct BLOCK {
    char[] ver         


        
5条回答
  •  长情又很酷
    2020-12-01 11:31

    Unless you really need a struct, you can do this with a class. A class is basically a struct, and will be used exactly the same way, but it can contain methods inside. One of these methods is the constructor, which will initialize default values inside it once you create a new instance with "new". To create a constructor, put a method with the same name of the class inside it. It may receive arguments if you wish.

    class RECORD 
    {  
    public int dt1;
    public char[] name; 
    public RECORD => name = new char[16] // if it is one-line the {} can be =>
    }
    
    class BLOCK 
        {
        public char[] version;
        public int  field1;
        public int  field2;
        public RECORD[] records;
        public char[] filler1;
        public BLOCK() 
            {
            records = new RECORD[15];
            filler1 = new char[24];
            version = new char[4];
            }      
        }
    

    This way when you create a new item of type BLOCK, it will be pre-initialized:

    var myblock = new BLOCK(); 
    Console.WriteLine(myblock.records.Length); // returns 15
    Console.WriteLine(myblock.records[0].Length); // returns 16
    Console.WriteLine(myblock.filler1.Length); // returns 24
    

提交回复
热议问题