c# - 什么 C# 功能允许使用 "object literal"类型表示法?

标签 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}                                             ||
}); //<------------------------------------------------------------------||

最佳答案

这是一个单一的功能 - collection initializers .与对象初始值设定项一样,它只能用作对象初始化表达式的一部分,但基本上它会使用任何存在的参数调用 Add - 使用大括号指定多个参数,或者一次指定单个参数而不用额外的大括号,例如

var list = new List<int> { 1, 2, 3 };

有关详细信息,请参阅 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();
    }
}

关于c# - 什么 C# 功能允许使用 "object literal"类型表示法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10132944/

相关文章:

asp.net - MVC 4 中的级联下拉列表

C# 字典包含Key

asp.net - WebAPI 返回 XML

c# - 为什么当visible变为false时JQuery无法获取Textarea值?

c# - 使用 C# 自动字母数字唯一 ID

c# - 此代码会导致过多的内存使用吗?

c# - .Net MVC 返回文件然后删除它

c++ - 将字值转换为具有设定值的键映射

c# - 在 C# 中初始化字典返回溢出错误

c# - @Parameter1 不是过程的参数