【问题标题】:Cannot implicitly convert type 'void' to 'System.Collections.Generic.Dictionary<string,bool>无法将类型 'void' 隐式转换为 'System.Collections.Generic.Dictionary<string,bool>
【发布时间】:2014-10-16 10:27:38
【问题描述】:

这段代码运行良好

Dictionary<string, bool> test = new Dictionary<string, bool>();
        test.Add("test string", true);

以下代码抛出此错误:无法将类型“void”隐式转换为“System.Collections.Generic.Dictionary”

Dictionary<string, bool> test = new Dictionary<string, bool>().Add("test string", true);

为什么?有什么区别?

【问题讨论】:

    标签: c# generics dictionary


    【解决方案1】:

    .Add的返回类型为void

    如果您正在链接调用,则最后一个表达式将成为整个语句的返回值。

    new Dictionary&lt;K, V&gt;() 的返回值是Dictionary&lt;K, V&gt;,然后你在它上面调用.Add.Add 什么也不返回(void

    您可以使用对象初始化器语法来内联执行此操作:

    Dictionary<string, bool> test = new Dictionary<string, bool> 
    { 
        { "test string", true } 
    };
    

    编辑:更多信息,很多流畅的语法风格框架将返回您调用该方法的对象以允许您链接:

    例如

    public class SomeFluentThing 
    {
       public SomeFluentThing DoSomething()
       {
           // Do stuff
           return this;
       }
    
       public SomeFluentThing DoSomethingElse()
       {
           // Do stuff
           return this;
       }
    
    }
    

    所以你可以自然地链接:

    SomeFluentThingVariable.DoSomething().DoSomethingElse();
    

    【讨论】:

    • agh.. 忘记检查返回类型。谢谢。
    【解决方案2】:

    Add() 方法的返回值类型不是 Dictionary 类的对象。您也不能将 Add() 方法的输出分配给测试对象。

    例如,您不能使用此代码:

    Dictionary<string, bool> test = new Dictionary<string, bool>();
    test = test.Add("test string", true); // Error
    

    【讨论】:

      【解决方案3】:

      Add() 的返回类型是void

      所以new Dictionary&lt;string, bool&gt;().Add("test string", true); 是无效的,您分配给Dictionary&lt;string, bool&gt; test,这导致了您的错误。

      Dictionary<string, bool> test = new Dictionary<string, bool>();
      test.Add("test string", true);
      

      另一方面,将新的Dictionary 分配给test,后者执行Add

      【讨论】:

        【解决方案4】:

        正如 Ali Sephri.Kh 所说,而

        new Dictionary<string, bool>();
        

        返回一个 Dictionary 实例,因此你的新变量可以赋值给它,Add 方法向新字典添加一个新值,并返回 void,因此不能赋值给你的新变量

        【讨论】:

          猜你喜欢
          • 2014-04-14
          • 2022-10-12
          • 1970-01-01
          • 2013-02-22
          • 1970-01-01
          • 1970-01-01
          • 2014-07-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多