gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:23:50 33 4
gpt4 key购买 nike

我正在学习 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com