我在C#相当新的,和一般的编码,所以有可能是一个明显的答案,这...在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"
我意识到可能有更好的方法来完成这个,但这不是一个重要的项目。我对这个问题的原理更感兴趣,而不是如何解决这个问题。
谢谢!
你可以创建你的类属性。在X的Get访问器中,检索Y和Z的值。 –