我想将此 C++ 代码转换为 C#:
typedef struct consoleCommand_s
{
char* cmd ;
void (*function)() ;
} consoleCommand_t ;
static consoleCommand_t commands[] =
{
{"clientlist", &CG__Clientlist},
{"say", &CG_Say},
{"nick", &CG_Nick},
{"logout", &CG_Logout}
} ;
// e.g.
static void CG_Logout(void)
{
// Logout
}
我最接近的是这个:
public class Class1
{
// public delegate int Calculate (int value1, int value2);
public delegate void fnCommand_t();
public class consoleCommand_t
{
public string strCommandName;
public fnCommand_t fnCommand;
public consoleCommand_t(string x, fnCommand_t y)
{
this.strCommandName = x;
this.fnCommand = y;
} // End Constructor
} // End Class consoleCommand_t
public static void Nick()
{
Console.WriteLine("Changing Nick");
} // End Sub
public static void Logout()
{
Console.WriteLine("Logging out");
} // End Sub
// string[] names = new string[] {"Matt", "Joanne", "Robert"};
public consoleCommand_t[] commands = new consoleCommand_t[] {
new consoleCommand_t("Nick", Nick),
new consoleCommand_t("Logout", Logout)
};
} // End Class Class1
现在我想问:
A) Why does Nick & Logout need to be static when all the rest is not ?
B) Is there no C-like way to initialize the commands array, that is, without new ?
最佳答案
您可以不在另一个类中创建一个类,而是在另一个类中管理您的默认控制台命令。
public delegate void ConsoleCmd();
public class DefaultCommands
{
public static void Nick()
{
Console.WriteLine("I'm Nick!");
}
public static void LogOut()
{
Console.WriteLine("You're Fired!");
}
}
public class Console
{
private Dictionary<string, ConsoleCmd> mCommands;
public Console()
{
mCommands = new Dictionary<string, ConsoleCmd>();
mCommands.Add("Nick", DefaultCommands.Nick);
mCommands.Add("Logout", DefaultCommands.LogOut);
}
}
访问您的命令就像:
ConsoleCmd command = mCommands["Nick"];
command();
编辑:未能提及这一点。这是为了向 OP 指出还有其他更好的方法可以实现他想做的事情。可能不会回答他的问题,但我希望能为他指明从函数式编程语言到纯面向对象语言的正确方向。
关于c# - 将结构数组从 C++ 转换为 C# 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5067519/