2014-02-19 31 views
0

我希望這不是一個愚蠢的問題,但我無法弄清楚這一點。根據按鍵更新字符串

我有一個準系統遊戲類:

public class Game1 : Game 
{ 
    GraphicsDeviceManager graphics; 
    SpriteBatch spriteBatch; 
    String inputHolder; 

    public Game1() 
     : base() 
    { 
     graphics = new GraphicsDeviceManager(this); 
     Content.RootDirectory = "Content"; 

     inputHolder = "Enter your keys: "; 
    } 

    protected override void Initialize() 
    { 
     base.Initialize(); 


     InputManager.stringToUpdate = inputHolder; 

    } 
    protected override void LoadContent() 
    { 
     spriteBatch = new SpriteBatch(GraphicsDevice); 
    } 

    protected override void UnloadContent() 
    { 
    } 

    protected override void Update(GameTime gameTime) 
    { 
     if (Keyboard.GetState().IsKeyDown(Keys.Escape)) 
     { 
      Exit(); 
     } 
     base.Update(gameTime); 

     InputManager.update(Keyboard.GetState()); 
    } 

    protected override void Draw(GameTime gameTime) 
    { 
     GraphicsDevice.Clear(Color.CornflowerBlue); 

     base.Draw(gameTime); 

     Console.WriteLine(inputHolder); 
    } 
} 

我也有一個輸入管理類:

static class InputManager 
{ 
    public static string stringToUpdate; 

    public static void update(KeyboardState kbState) 
    { 
     if (stringToUpdate != null) 
     { 
      foreach (Keys k in kbState.GetPressedKeys()) 
      { 
       stringToUpdate += k.ToString(); 
      } 
     } 
    } 
} 

但是無論我按什麼鍵原始字符串inputHolder不受影響,即使字符串在C#中作爲參考類型處理。

我試過改變 InputManager.stringToUpdate = inputHolder; 至 InputManager.stringToUpdate = ref inputHolder; 並沒有任何反應。

缺少什麼我在這裏?

+1

字符串是不可變的。傳遞字符串時,您傳遞的是其內容的引用,而不是「指向內容的指針的指針」。您需要引用'inputHolder'引用才能更新它。但你不能。 看看這個:http://stackoverflow.com/questions/636932/in-c-why-is-string-a-reference-type-that-behaves-like-a-value-type – BatteryBackupUnit

回答

0

如前所述,字符串是不可變的。包裝類中的inputHolder字符串將帶來所需的效果:

public class InputHolder 
{ 
    public string Input { get; set; } 
} 

public class Game1 : Game 
{ 
    GraphicsDeviceManager graphics; 
    SpriteBatch spriteBatch; 
    InputHolder inputHolder = new InputHolder(); 

    public Game1() 
     : base() 
    { 
     graphics = new GraphicsDeviceManager(this); 
     Content.RootDirectory = "Content"; 

     inputHolder.Input = "Enter your keys: "; 
    } 

    protected override void Initialize() 
    { 
     base.Initialize(); 
     InputManager.inputHolderToUpdate = inputHolder; 
    } 

    // etc 

    protected override void Draw(GameTime gameTime) 
    { 
     GraphicsDevice.Clear(Color.CornflowerBlue); 
     base.Draw(gameTime); 
     Console.WriteLine(inputHolder.Input); 
    } 
} 

static class InputManager 
{ 
    public static InputHolder inputHolderToUpdate; 

    public static void update(KeyboardState kbState) 
    { 
     if (inputHolderToUpdate != null) 
     { 
      foreach (Keys k in kbState.GetPressedKeys()) 
      { 
       inputHolderToUpdate.Input = inputHolderToUpdate.Input + k.ToString(); 
      } 
     } 
    } 
}