2013-07-25 45 views
1

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

我意識到可能有更好的方法來完成這個,但這不是一個重要的項目。我對這個問題的原理更感興趣,而不是如何解決這個問題。

謝謝!

+0

你可以創建你的類屬性。在X的Get訪問器中,檢索Y和Z的值。 –

回答

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 
+0

謝謝您提供清晰而徹底的答案!這對我的方法來說絕對是一個巨大的改進。 – rockyourteeth

5

,你可以讓你的變量,而不是

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

通常可以使用屬性此

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

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