首页 文章

C#不可变类和游戏对象

提问于
浏览
1

我正在做一些关于在java中创建不可变对象的here,我想知道,在某些情况下创建一个可变对象是否可以?

例如,假设我们在C#中创建一个乒乓球游戏,显然,我们会有一个代表球的类,而两个桨,你会像这样编写球类:

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属性不是更好吗?在这种情况下使它变得有意义吗?你会怎么做?

1 回答

  • 5

    如果您使用的是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; }
        }
    

    这样,你仍然可以在类中编写方法来改变属性,但是类之外的任何东西都不能改变它们的值 .

相关问题