【问题标题】:Global Variable Vs. Set Function全局变量与。设置功能
【发布时间】:2015-07-20 16:58:20
【问题描述】:

我正在寻找在另一个类中更改变量值的最佳编程实践。

例如,如果我有一个布尔值来确定敌人是否面向左侧,那么最好的方法是什么?

一个

*outside of Class*
Class.Right = false;

*inside of Class*
public Right = true;

B

*outside of Class*
Class.setRight(false);

*inside of Class*
private Right = true;
public void setRight (right) {
    Right = right;
}

另外,我读到你应该避免一起使用全局变量,但在这种情况下你应该使用它,因为它在类中的多个函数中使用,对吧?

【问题讨论】:

  • 那不是全局变量,是公共成员变量。在 C# 中设置函数没有意义,因为您只能使用属性。
  • 好的,我会坚持使用 A。我认为在这个级别为每个变量实现属性没有意义。

标签: c# function oop global-variables global


【解决方案1】:

使用枚举,你可以选择它的设置方式(我们需要了解实现细节以提供具体建议)。

public enum DirectionType{ Right, Left };

public class Enemy
{
    public DirectionType Direction{ get; set; }

    public void HoneInOnHero()
    {
        //Hero's function can help determine position relative to the enemy.
        this.Direction = Hero.GetRelativeDirection(this);
    }
}

var enemy = new Enemy();
enemy.Direction = DirectionType.Left;
//or...
if(attackMode)
    enemy.HoneInOnHero();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2010-10-03
    • 2019-07-18
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多