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; 並沒有任何反應。
缺少什麼我在這裏?
字符串是不可變的。傳遞字符串時,您傳遞的是其內容的引用,而不是「指向內容的指針的指針」。您需要引用'inputHolder'引用才能更新它。但你不能。 看看這個:http://stackoverflow.com/questions/636932/in-c-why-is-string-a-reference-type-that-behaves-like-a-value-type – BatteryBackupUnit