Sob*_*aku 2 c# class constructor-overloading
我正在学习 C# 并制作了一个简单的“播放器”类。但我很难有多重超载。这是我最好的解决方案,但我觉得它可以做得更简单/更好。
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;
}
Run Code Online (Sandbox Code Playgroud)
好不好,如果不好,请告诉我为什么。感谢您的回复!
我认为这很好。要问自己一个问题:这些方法中的每一个实际上都有可能被调用吗?
一种选择是让程序员在实例化类后设置这些值:
var myPlayer = new Player();
myPlayer.XP = 5;
Run Code Online (Sandbox Code Playgroud)
但是,在某些情况下,您确实需要预先获得所有信息,因此这可能并不合适。
另一个选项可能是传递给 ctor 的选项类:
public class PlayerSettings
{
public Name = "Player";
public XP = 0;
public LVL = 1;
public XPToLvlUp = 10;
public XpRank = 10;
}
Run Code Online (Sandbox Code Playgroud)
然后你的ctors看起来像这样:
public Player() : this(new PlayerSettings())
{
}
public Player(PlayerSettings settings)
{
//Fill in appropriate variables here
}
Run Code Online (Sandbox Code Playgroud)
该选项将以这种方式调用:
var playerSettings = new PlayerSettings() { XP = 5 };
var myPlayer = new Player(playerSettings());
Run Code Online (Sandbox Code Playgroud)
最后,我不确定一个比另一个“更好”,这在很大程度上取决于您的需求。