在C#中,我可以根据构成变量的变量创建一个更新其值的变量吗?

时间:2013-07-25 00:18:13

标签: c# variables

我对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"

我意识到可能有更好的方法来实现这一目标,但这不是一个重要的项目。我对问题的原理比对如何解决这个特殊问题更感兴趣。

谢谢!

3 个答案:

答案 0 :(得分:8)

您想要使用封装模型的类:

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))
            );
        }
    }
}

用法:

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);

输出:

Player
Super Player
Super Player is Alive
Player is Dead

答案 1 :(得分:5)

你可以改变你的变量属性

public string X
{
    get { return Y + Z; }
}

答案 2 :(得分:1)

通常,您可以为此

使用属性
public string Salutation { get; set; }
public string Name { get; set; }

public string Greeting 
{ 
  get { return string.Format("{0}, {1}!", Salutation, Name); } 
}