无法将类型'void'隐式转换为'System.Collections.Generic.Dictionary <string,bool> </string,bool>

时间:2014-10-16 10:27:38

标签: c# generics dictionary

此代码可以正常使用

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

以下代码抛出此错误:无法隐式转换类型&#39; void&#39;到&#39; System.Collections.Generic.Dictionary

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

为什么呢?有什么区别?

4 个答案:

答案 0 :(得分:5)

.Add的返回类型为void

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

new Dictionary<K, V>()的返回值为Dictionary<K, V>,然后您在其上调用.Add.Add不返回任何内容(void

您可以使用对象初始化程序语法进行内联:

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

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

e.g。

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

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

}

所以你可以自然地链接:

SomeFluentThingVariable.DoSomething().DoSomethingElse();

答案 1 :(得分:0)

Add()方法的返回值类型不是Dictionary类的对象。此外,您无法将Add()方法的输出分配给测试对象。<​​/ p>

例如,无法使用此代码:

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

答案 2 :(得分:0)

Add()的返回类型为void

因此new Dictionary<string, bool>().Add("test string", true);无法分配给Dictionary<string, bool> test,导致您的错误。

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

将新Dictionary分配给test,后者执行Add

答案 3 :(得分:0)

正如Ali Sephri.Kh所说,而

new Dictionary<string, bool>();

返回一个Dictionary实例,因此可以为你的新变量赋值,Add方法为新词典添加一个新值,并返回void,因此无法分配给你的新变量

相关问题