Mutable struct vs. class?

后端 未结 3 1312
轮回少年
轮回少年 2021-02-11 00:33

I\'m unsure about whether to use a mutable struct or a mutable class. My program stores an array with a lot of objects. I\'ve noticed that using a class doubles the amount of me

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-11 01:24

    Do they really have to be mutable? You could always make it an immutable struct with methods to create a new value with one field different:

    struct Block
    {
        // I'd definitely get rid of the HasMetaData
        private readonly byte id;
        private readonly BlockMetaData metaData;
    
        public Block(byte id, BlockMetaData metaData)
        {
            this.id = id;
            this.metaData = metaData;
        }
    
        public byte Id { get { return id; } }
        public BlockMetaData MetaData { get { return metaData; } }
    
        public Block WithId(byte newId)
        {
            return new Block(newId, metaData);
        }
    
        public Block WithMetaData(BlockMetaData newMetaData)
        {
            return new Block(id, newMetaData);
        }
    }
    

    I'm still not sure whether I'd make it a struct, to be honest - but I'd try to make it immutable either way, I suspect.

    What are your performance requirements in terms of both memory and speed? How close does an immutable class come to those requirements?

提交回复
热议问题