C#功能允许使用"对象文字"类型表示法?

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)

Jon*_*eet 8

它是一个单一的功能 - 集合初始化器.与对象初始化器一样,它只能用作对象初始化表达式的一部分,但基本上它Add使用任何存在的参数进行调用- 使用大括号指定多个参数,或者在没有额外大括号的情况下使用单个参数,例如

var list = new List<int> { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅C#4规范的第7.6.10.3节.

请注意,编译器需要两种类型的东西才能用于集合初始值设定项:

  • 它必须实现IEnumerable,尽管编译器不会生成任何调用GetEnumerator
  • 它必须具有适当的Add方法重载

例如:

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)

  • @JonSkeet应用敏捷原理来回答StackOverflow问题,是吗?嗯.;) (3认同)
  • 至少在答案中我们有一个指向MSDN文档的链接.:) (2认同)

Ry-*_*Ry- 7

这是集合初始化语法.这个:

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

  • "字典初始化语法"使其听起来像C#*作为一种语言*具有内置的字典知识.它没有.它将与*any*类型一起使用,它实现了`IEnumerable`并具有适当的`Add`方法. (4认同)
  • @minitech:没有.它认识到有一个`Add(key,value)`方法.有关此示例,请参阅我的答案.另请注意,实际上,变量仅在*Add`调用之后被赋值* - 就好像你之前有一个临时变量一样. (3认同)