加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将struct数组从C转换为C#的问题

发布时间:2020-12-16 09:32:48 所属栏目:百科 来源:网络整理
导读:我想将此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.
我想将此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 ?

解决方法

你可以不用另一个类INSIDE,并在另一个类中管理你的默认控制台命令.

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有其他更好的方法来实现他想做的事情.并且可能没有回答他的问题,但我希望在他从功能编程语言转换为纯面向对象语言方面指向正确的方向.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读