我希望这不是一个愚蠢的问题,但我无法弄明白。
我有一个准系统游戏类:
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; 没有任何反应。
我在这里缺少什么?
答案 0 :(得分: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();
}
}
}
}