1

I'm pretty new at C#, and coding in general, so there might be an obvious answer to this...

If I have a variable (X) that is equivalent to some other variables concatenated (Y and Z) (or added together, or whatever), how can I make X so that each time I use it, it gets any changes that Y and Z may have had.

Is that possible?

Here's my code. Here, I just kept updating the variable, but it'd be nice if I didn't have to keep doing that.

        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"

I realize that there's probably a better way to accomplish this, but this isn't an important project. I'm more curious about the principle of the question than about how to solve this particular problem.

Thanks!

4

3 回答 3

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
于 2013-07-25T00:22:48.857 回答
5

你可以让你的变量成为一个属性

public string X
{
    get { return Y + Z; }
}
于 2013-07-25T00:22:08.457 回答
1

通常,您可以为此使用属性

public string Salutation { get; set; }
public string Name { get; set; }

public string Greeting 
{ 
  get { return string.Format("{0}, {1}!", Salutation, Name); } 
}
于 2013-07-25T00:23:36.283 回答