How to deal with the immutability of returned structs?

前端 未结 6 1883

I\'m writing a game that has a huge 2D array of \"cells\". A cell takes only 3 bytes. I also have a class called CellMap, which contains the 2D array as a private field, and pro

6条回答
  •  死守一世寂寞
    2021-02-04 17:19

    If you want to make Cell immutable - as you should if it is a struct - then a good technique is to make a factory that is an instance method on the Cell:

    struct C
    {
        public int Foo { get; private set; }
        public int Bar { get; private set; }
        private C (int foo, int bar) : this()
        {
            this.Foo = foo;
            this.Bar = bar;
        }
        public static C Empty = default(C);
        public C WithFoo(int foo)
        {
            return new C(foo, this.Bar);
        }
        public C WithBar(int bar)
        {
            return new C(this.Foo, bar);
        }
        public C IncrementFoo()
        {
            return new C(this.Foo + 1, bar);
        }
        // etc
    }
    ...
    C c = C.Empty;
    c = c.WithFoo(10);
    c = c.WithBar(20);
    c = c.IncrementFoo();
    // c is now 11, 20
    

    So your code would be something like

    map[x,y] = map[x,y].IncrementPopulation();
    

    However, I think this is possibly a blind alley; it might be better to simply not have so many Cells around in the first place, rather than trying to optimize a world where there are thousands of them. I'll write up another answer on that.

提交回复
热议问题