【问题标题】:C# - Dictionary<String, Action> No overload for method 'Add' takes 1 argumentsC# - Dictionary<String, Action> 方法 'Add' 没有重载需要 1 个参数
【发布时间】:2015-01-24 22:28:28
【问题描述】:

嗯,我正在尝试在我的项目中做点什么。它是基于网络的,我使用字典来处理我的数据包前缀。

“Add”方法没有重载需要 1 个参数 无论如何,这是我的代码:

    private Dictionary<string, Action> worldPackets = new Dictionary<string, Action>
    {
        "jr", User.HandleJoinRoom,
        "sm", User.HandleSendMessage,
        "cr", User.HandleCreateRoom
    };

谢谢。

【问题讨论】:

  • 仅仅因为您将两个值放在同一行并不能使其成为键值条目。

标签: c# string dictionary action


【解决方案1】:

你需要使用花括号来分隔每一对

private Dictionary<string, Action> worldPackets = new Dictionary<string, Action>
{
    { "jr", User.HandleJoinRoom },
    { "sm", User.HandleSendMessage },
    { "cr", User.HandleCreateRoom }
};

【讨论】:

  • 无法从方法组转换为操作。
  • “User.HandleJoinRoom”是一个方法组(一个函数?),而不是一个“Action”。
  • @JoãoMiguelBrandão 给你的作业:编译它并思考它为什么有效。 void AMethod() { } void AnotherMethod() { Dictionary&lt;string, Action&gt; worldPackets = new Dictionary&lt;string, Action&gt;() { {"a",AMethod} }; }
  • 好吧,对不起,User.HandleJoinRoom 会是什么类型的变量呢?
  • @JoãoMiguelBrandão 然后试试这个:public class User { public static void AMethod() { Console.WriteLine("aa"); } } void AnotherMethod() { Dictionary&lt;string, Action&gt; worldPackets = new Dictionary&lt;string, Action&gt;() { {"a", User.AMethod} }; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
相关资源
最近更新 更多