C# 不可变 类 和游戏对象

C# Immutable Classes and Gaming Objects

我正在阅读 关于在 java 中创建不可变对象的内容,我想知道,在某些情况下可以创建可变对象吗?

例如,假设我们正在用 C# 创建一个乒乓球游戏,显然,我们会有一个 class 代表一个球,还有两个球拍,你会把球写成 class 像这样:

 class Ball
    {
        private readonly int xPosition;
        private readonly int yPosition;
        private readonly int ballSize;
        private readonly string ballColor;

        public Ball(int x, int y, int size, string color)
        {
            this.xPosition=x;
            this.yPosition=y;
            this.ballSize = size;
            this.ballColor = color;
        }

        public int getX
        {
            get
            {
                return this.xPosition;
            }
        }
        //left out rest of implementation.

或者像这样:

    class Ball
    {
        private int xPosition;
        private int yPosition;
        private int ballSize;
        private string ballColor;

        public Ball(int x, int y, int size, string color)
        {
            this.xPosition=x;
            this.yPosition=y;
            this.ballSize = size;
            this.ballColor = color;
        }

        public int getX
        {
            get
            {
                return this.xPosition;
            }

            set
            {
                this.xPosition = value;
            }
        }


    }
}

在我们的对象(球)可以改变位置、大小(根据级别变小或变大)和颜色的情况下,提供一个 setter 属性 不是更好吗?在这种情况下,使其可变有意义吗?你会如何处理这个问题?

如果您使用的是 C#,则无需通过创建单独的字段来使对象不可变的开销。相反,你可以这样做 -

    class Ball
    {
         public Ball ( int x, int y, int size, string color) 
         { ... }
         public int XPos {get; private set; }
         public int YPos {get; private set; }
         public int Size {get; private set; }
         public string BallColor {get; private set; }
    }

这样,您仍然可以在 class 中编写方法来改变属性,但 class 之外的任何内容都不能更改它们的值。