Jan*_*ray 6 c# asp.net-mvc dictionary routevalues
我来自JavaScript,我知道这{ }是一个对象字面值,不需要new Object调用; 我想知道这{"id",id}, {"saveChangesError",true}部分是否与C#相同.
我知道这里有两个C#功能,请向我解释一下它们是什么?
new RouteValueDictionary()
{ //<------------------------------[A: what C# feature is this?] -------||
{"id",id}, //<------------------[B: what C# feature is this also?] ||
{"saveChangesError",true} ||
}); //<------------------------------------------------------------------||
Run Code Online (Sandbox Code Playgroud)
它是一个单一的功能 - 集合初始化器.与对象初始化器一样,它只能用作对象初始化表达式的一部分,但基本上它Add使用任何存在的参数进行调用- 使用大括号指定多个参数,或者在没有额外大括号的情况下使用单个参数,例如
var list = new List<int> { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅C#4规范的第7.6.10.3节.
请注意,编译器需要两种类型的东西才能用于集合初始值设定项:
IEnumerable,尽管编译器不会生成任何调用GetEnumeratorAdd方法重载例如:
using System;
using System.Collections;
public class Test : IEnumerable
{
static void Main()
{
var t = new Test
{
"hello",
{ 5, 10 },
{ "whoops", 10, 20 }
};
}
public void Add(string x)
{
Console.WriteLine("Add({0})", x);
}
public void Add(int x, int y)
{
Console.WriteLine("Add({0}, {1})", x, y);
}
public void Add(string a, int x, int y)
{
Console.WriteLine("Add({0}, {1}, {2})", a, x, y);
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotSupportedException();
}
}
Run Code Online (Sandbox Code Playgroud)
这是集合初始化语法.这个:
RouteValueDictionary d = new RouteValueDictionary()
{ //<-- A: what C# feature is this?
{"id",id}, //<-- B: what C# feature is this also?
{"saveChangesError",true}
});
Run Code Online (Sandbox Code Playgroud)
基本上相当于这个:
RouteValueDictionary d = new RouteValueDictionary();
d.Add("id", id);
d.Add("saveChangesError", true);
Run Code Online (Sandbox Code Playgroud)
编译器认识到它实现IEnumerable并具有适当的Add方法并使用它的事实.
请参阅:http://msdn.microsoft.com/en-us/library/bb531208.aspx