2014-10-16 88 views

回答

4

.Add返回类型是void

,最后一个表达式成为整个语句的返回值。

new Dictionary<K, V>()返回值是Dictionary<K, V>,然后调用.Add它,.Add返回任何(void

您可以使用对象初始化器语法来做到这一点在线:

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

编辑:更多info,许多流利的语法样式框架将返回您称为方法的对象以允许您链接:

eg

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

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

} 

这样你就可以自然链:

SomeFluentThingVariable.DoSomething().DoSomethingElse(); 
+0

agh ..忘了检查返回类型。谢谢。 – PSR 2014-10-16 10:32:27

0

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

比如你不能使用此代码:如果您链接调用

Dictionary<string, bool> test = new Dictionary<string, bool>(); 
test = test.Add("test string", true); // Error 
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); 

,另一方面分配新的Dictionarytest和后者进行Add

0

阿里Sephri.Kh一边说,一边

new Dictionary<string, bool>(); 

回报字典实例,因此您的新的变量可以分配给它,Add方法将新值添加到新字典中,并返回void,因此不能分配给您的新变量

相关问题