c#不可变类和游戏对象

本文关键字:游戏 对象 不可变 | 更新日期: 2023-09-27 18:02:30

我在这里做了一些关于在java中创建不可变对象的阅读,我想知道,在某些情况下创建可变对象是可以的吗?

例如,假设我们正在用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属性不是更好吗?在这种情况下,让它可变有意义吗?你会如何处理这个问题?

c#不可变类和游戏对象

如果您正在使用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; }
    }

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