C# 基于按键更新字符串
我希望这不是一个愚蠢的问题,但我想不出来 我有一门赤骨游戏课:C# 基于按键更新字符串,c#,monogame,C#,Monogame,我希望这不是一个愚蠢的问题,但我想不出来 我有一门赤骨游戏课: public class Game1 : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; String inputHolder; public Game1() : base() { graphics = new GraphicsDeviceManager(this);
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);
}
}
我还有一个InputManager类:
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字符串将获得所需的效果:
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();
}
}
}
}
字符串是不可变的。传递字符串时,传递的是对其内容的引用,而不是“指向内容指针的指针”。您需要对
inputHolder
引用的引用才能对其进行更新。但你不能。看看这个: