2
我使用XNA作爲我的遊戲框架。在我Input
類,我使用XNA來獲取鍵盤狀態並檢測按鍵:在單獨的命名空間中處理重複類的最佳做法
namespace MyGame.Classes
{
public class Input : IInput
{
public bool DetectKey(Keys key)
{
if (Keyboard.GetState().IsKeyDown(key))
{
return true;
}
return false;
}
}
}
最近我一直在試圖整合Newtonsoft.Json爲我的遊戲管理的配置設置。在另一類,我讀的JSON文件:
{
"Settings": {
// ...
},
"Controls": {
"Keyboard": {
"W": "Up",
"A": "Left",
"S": "Down",
"D": "Right"
}
}
}
然後我投的JSON到一個強類型的對象:
namespace MyGame.Classes
{
public class Config
{
public Settings Settings = new Settings();
public Controls Controls = new Controls();
}
public class Controls
{
public Keyboard Keyboard = new Keyboard();
}
public class Keyboard
{
public string W = "Default";
public string A = "Default";
public string S = "Default";
public string D = "Default";
}
}
我遇到的問題是我想用兩個Keyboard
類(在我Input
類MyGame.Classes.Keyboard
和Microsoft.Xna.Framework.Input.Keyboard
)是這樣的:
namespace MyGame.Classes
{
public class Input : IInput
{
public bool DetectUp(Config config)
{
// Convert string to enum
var key = GetKey(config.Controls.Keyboard.W);
return DetectKey(key);
}
}
}
顯然編譯器不開心這件事。我一直在尋找解決方案,但大多數問過這個問題的人都可以控制這兩個名稱空間。我不知道如何將任何這些解決方案適應我的情況:
- Namespace and Class Naming Best Practice in Atypical System
- Separate projects or multiple class files ... namespace best practice in C#
- Identical class names in different namespaces
我嘗試添加這的Input
頂部:
using Keyboard = Microsoft.Xna.Framework.Input.Keyboard;
using KeyboardConfig = MyGame.Classes.Keyboard;
這不起作用,因爲c ompiler仍嘗試使用MyGame.Classes.Keyboard
來解析類中的每個Keyboard
。
對我來說最好的辦法是什麼?
This works。但是我並沒有爲XNA的'Keyboard'類的每個用法加前綴而瘋狂,所以我最終將'MyGame.Classes.Config'和相關的類移動到了另一個名稱空間'MyGame.Settings'。然後,我可以在我的Input類中添加'使用Keyboard = Microsoft.Xna.Framework.Input.Keyboard;',一切正常。 –