Using structs in C# to read data

前端 未结 2 1251
清歌不尽
清歌不尽 2021-01-26 19:46

Say I have a struct defined as such

struct Student
{
  int age;
  int height;
  char[] name[12];
}

When I\'m reading a binary file, it looks so

相关标签:
2条回答
  • 2021-01-26 20:01

    If you want to serialize / deserialize the struct

    If you want to read/write the entire struct to a binary file (serialization), I suggest you look at

    https://stackoverflow.com/a/629120/141172

    Or, if it is an option for you, follow @Marc's advice and use a cross-platform serializer. Personally I would suggest protobuf-net which just happens to have been written by @Marc.

    If you are loading from an arbitrary file format

    Just like a class, a struct can have a constructor that accepts multiple parameters. In fact, it is generally wise to not provide setters for a struct. Doing so allows the values of the struct to be changed after it is constructed, which generally leads to programming bugs because many developers fail to appreciate the fact that struct is a value type with value semantics.

    I would suggest providing a single constructor to initialize your struct, reading the values from the file into temporary variables, and then constructing the struct with a constructor.

    public stuct MyStruct
    {
        public int Age { get; private set; }
        public int Height { get; private set; }
        private char[] name;
        public char[] Name 
        {
            get { return name; }
            set
            {
                if (value.Length > 12) throw new Exception("Max length is 12");
                name = value;
            }
        }
        public MyStruct(int age, int height, char[] name)
        {
        }
    }
    

    To dig further into the perils of mutable structs (ones that can be changed after initialized) I suggest

    Why are mutable structs “evil”?

    0 讨论(0)
  • 2021-01-26 20:13

    There is not, AFAIK, a low-level direct-layout struct reader built into .NET. You would want want to look at BinaryReader, reading each field in turn? Basically, ReadInt32() twice, and ReadChars(). Pay particular attention to the encoding of the character data (ASCII? UTF8? UTF-16?) and the endianness of the integers.

    Personally, I'd look more at using a dedicated cross-platform serializer!

    0 讨论(0)
提交回复
热议问题