我对C#很新,而且编码一般,所以可能有一个明显的答案......
如果我有一个变量(X)等同于连接的一些其他变量(Y和Z)(或者加在一起,或者其他什么),我如何制作X以便每次使用它时,它都会得到Y和Z可能有过.
那可能吗?
这是我的代码.在这里,我只是不断更新变量,但如果我不必继续这样做,那就太好了.
string prefix = "";
string suffix = "";
string playerName = "Player";
string playerNameTotal = prefix + playerName + suffix;
// playerNameTotal is made up of these 3 variables
Console.WriteLine(playerNameTotal); // Prints "Player"
prefix = "Super ";
playerNameTotal = prefix + playerName + suffix; // I want to not have to use this line
Console.WriteLine(playerNameTotal); // Prints "Super Player"
suffix = " is Alive";
playerNameTotal = prefix + playerName + suffix; // I want to not have to use this line
Console.WriteLine(playerNameTotal); // Prints "Super Player is Alive"
suffix = " is Dead";
prefix = "";
playerNameTotal = prefix + playerName + suffix; // I want to not have to use this line
Console.WriteLine(playerNameTotal); // Prints "Player is Dead"
Run Code Online (Sandbox Code Playgroud)
我意识到可能有更好的方法来实现这一目标,但这不是一个重要的项目.我对问题的原理比对如何解决这个特殊问题更感兴趣.
谢谢!
您想使用封装模型的类:
class PlayerName {
public string Prefix { get; set; }
public string Name { get; set; }
public string Suffix { get; set; }
public string PlayerNameTotal {
get {
return String.Join(
" ",
new[] { this.Prefix, this.Name, this.Suffix }
.Where(s => !String.IsNullOrEmpty(s))
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
PlayerName playerName = new PlayerName {
Prefix = "",
Name = "Player",
Suffix = ""
};
Console.WriteLine(playerName.PlayerNameTotal);
playerName.Prefix = "Super";
Console.WriteLine(playerName.PlayerNameTotal);
playerName.Suffix = "is Alive";
Console.WriteLine(playerName.PlayerNameTotal);
playerName.Prefix = "";
playerName.Suffix = "is Dead";
Console.WriteLine(playerName.PlayerNameTotal);
Run Code Online (Sandbox Code Playgroud)
输出:
Player
Super Player
Super Player is Alive
Player is Dead
Run Code Online (Sandbox Code Playgroud)