c# - 在 C# 中编写多个构造函数重载的最佳方法

标签 c# class constructor-overloading

我正在学习 C#,并制作了一个简单的“Player”类。但我很难承受多重重载。 这是我最好的解决方案,但我觉得它可以做得更简单/更好。

class Player : Entity
    {
        public Player() {
            Name = "Player";
            XP = 0;
            LVL = 1;
            XPToLvlUp = 10;
            XpRank = 10;
        }

        public Player(string name) : this() {
            Name = name;
        }

        public Player(string name, int _Hp, int _Mp) : this(name) {
            HP = _Hp;
            MP = _Mp;
        }

        public Player(string name, int _Hp, int _Mp, int _Xp, int _Lvl) : this(name, _Hp, _Mp) {
            XP = _Xp;
            LVL = _Lvl;
        }

        public Player(string name, int _Hp, int _Mp, int _Xp, int _Lvl, int XpByRank) : this(name, _Hp, _Mp, _Xp, _Lvl) {
            XpRank = XpByRank;
        }

        //deleted code for better reading

        private int XPToLvlUp;
        private int XpRank;
        public int XP;
        public int LVL;
        public string Name;
    }  

好不好,如果不好请告诉我原因。 感谢您的回复!

最佳答案

我觉得这样就很好了。要问自己一个问题:这些方法中的每一种实际上都可能被调用吗?

一种选择是让程序员在实例化类后设置这些值:

var myPlayer = new Player();
myPlayer.XP = 5;

但是,在某些情况下,您确实希望预先获得所有信息,因此这可能不合适。

另一个选项可以是传递给构造函数的选项类:

public class PlayerSettings
{
  public Name = "Player";
  public XP = 0;
  public LVL = 1;
  public XPToLvlUp = 10;
  public XpRank = 10; 
}

然后你的 Actor 看起来像这样:

public Player() : this(new PlayerSettings())
{
}

public Player(PlayerSettings settings)
{
  //Fill in appropriate variables here
}

该选项将以这种方式调用:

var playerSettings = new PlayerSettings() { XP = 5 };
var myPlayer = new Player(playerSettings());

最后,我不确定一个比另一个“更好”,这很大程度上取决于您的需求。

关于c# - 在 C# 中编写多个构造函数重载的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61646032/

相关文章:

c# - UWP 访问现有页面实例

class - 如果我有实例列表,调用类函数的 Pythonic 方式

java - 除了构造函数重载java之外的最佳实践/设计模式

c# - ubuntu 中 vscode 中的 oracle 连接

c# - DotLiquid - 检查字符串 "null or empty"

c# - 我的统一着色器的问题

python - 如何将我的 Python 文件分离到多个插件?

java - 从另一个调用一个构造函数,在 Java 中重载

c++ - 可选引用成员——这可能吗?

c# - 如何解决 20/3 是 6.666 和 6.667 的问题?