不能将类型'void'隐式转换为'System.Collections.Generic.Dictionary< string,bool> [英] Cannot implicitly convert type 'void' to 'System.Collections.Generic.Dictionary<string,bool>

查看:770
本文介绍了不能将类型'void'隐式转换为'System.Collections.Generic.Dictionary< string,bool>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码正常工作

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

以下代码引发此错误:无法隐式地将类型'void'转换为'System.Collections.Generic 。字典

 字典< string,bool> test = new Dictionary< string,bool>()。Add(test string,true); 

为什么?有什么区别?

解决方案

.Add 的返回类型是 void



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



新的Dictionary< K,V>()的返回值是 Dictionary< K,V> ; ,然后你调用 .Add 并且 .Add 不返回任何东西(<$
$ b 您可以使用对象初始化语法来执行此操作:

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

编辑:更多信息,许多流利的语法样式框架将返回您称为方法的对象让您连锁:



例如

  public class SomeFluentThing 
{
public SomeFluentThing DoSomething()
{
//做东西
返回这个;
}

public SomeFluentThing DoSomethingElse()
{
//做东西
return this;
}

}

所以你可以自然地链接:

  SomeFluentThingVariable.DoSomething()。DoSomethingElse(); 


This code works fine

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

The following code throws this error : Cannot implicitly convert type 'void' to 'System.Collections.Generic.Dictionary

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

why? what is the difference?

解决方案

The return type of .Add is void

If you are chaining calls, the last expression becomes the return value of the whole statement.

The return value of new Dictionary<K, V>() is Dictionary<K, V>, then you call .Add on it and .Add returns nothing (void)

You can use object initialiser syntax to do this inline:

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

Edit: more info, a lot of fluent syntax style frameworks will return the object you called the method on to allow you to chain:

e.g.

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

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

}

So you can chain naturally:

SomeFluentThingVariable.DoSomething().DoSomethingElse();

这篇关于不能将类型'void'隐式转换为'System.Collections.Generic.Dictionary&lt; string,bool&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆