PSR*_*PSR -2 c# generics dictionary
该代码可以正常工作
Dictionary<string, bool> test = new Dictionary<string, bool>();
test.Add("test string", true);
Run Code Online (Sandbox Code Playgroud)
以下代码引发此错误:无法将类型“ void”隐式转换为“ System.Collections.Generic.Dictionary”
Dictionary<string, bool> test = new Dictionary<string, bool>().Add("test string", true);
Run Code Online (Sandbox Code Playgroud)
为什么?有什么不同?
的返回类型.Add为void
如果要链接调用,则最后一个表达式将成为整个语句的返回值。
返回值为new Dictionary<K, V>()is Dictionary<K, V>,然后调用.Add它,不.Add返回任何值(void)
您可以使用对象初始化程序语法进行内联:
Dictionary<string, bool> test = new Dictionary<string, bool>
{
{ "test string", true }
};
Run Code Online (Sandbox Code Playgroud)
编辑:更多信息,许多流畅的语法样式框架将返回您调用方法的对象,以允许您链接:
例如
public class SomeFluentThing
{
public SomeFluentThing DoSomething()
{
// Do stuff
return this;
}
public SomeFluentThing DoSomethingElse()
{
// Do stuff
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,您可以自然地链接:
SomeFluentThingVariable.DoSomething().DoSomethingElse();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3564 次 |
| 最近记录: |