English 中文(简体)
为什么我开始把像C#中一个阵列这样的名单。
原标题:Why can I initialize a List like an array in C#?

今天,我感到惊讶的是,在C# I中可以做到:

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

为什么我能这样做? 所谓的“谁”? 我如何用我自己的班子这样做? 我知道,这是启动阵列的方法,但阵列是语言项目,名单是简单的物体......

最佳回答

This is part of the collection initializer syntax in .NET. You can use this syntax on any collection you create as long as:

  • 它实施<条码> 可计算(最好<条码>,可计算和提用;T>)

  • It has a method named Add(...)

发生的情况是,要求设违约建筑商,然后要求开标人每个成员填写Add(......)

因此,这两个区块大致相同:

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

而且

List<int> temp = new List<int>();
temp.Add(1);
temp.Add(2);
temp.Add(3);
List<int> a = temp;

阁下:

// Notice, calls the List constructor that takes an int arg
// for initial capacity, then Add() s three items.
List<int> a = new List<int>(3) { 1, 2, 3, }

注:Add(>) 方法不需要一个单一项目,例如Add(<>>/code> >,;TKey,telalue>有两个项目:

var grades = new Dictionary<string, int>
    {
        { "Suzy", 100 },
        { "David", 98 },
        { "Karen", 73 }
    };

基本相同:

var temp = new Dictionary<string, int>();
temp.Add("Suzy", 100);
temp.Add("David", 98);
temp.Add("Karen", 73);
var grades = temp;

因此,为了给你自己的班子添加这一点,如上所述,你需要做的是执行<条码>。 缩略语

public class SomeCollection<T> : IEnumerable<T>
{
    // implement Add() methods appropriate for your collection
    public void Add(T item)
    {
        // your add logic    
    }

    // implement your enumerators for IEnumerable<T> (and IEnumerable)
    public IEnumerator<T> GetEnumerator()
    {
        // your implementation
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

然后,你可以像《维也纳条约法公约》的收集那样使用:

public class MyProgram
{
    private SomeCollection<int> _myCollection = new SomeCollection<int> { 13, 5, 7 };    

    // ...
}

(详情见MSDN

问题回答

It is so called syntactic sugar.

List<T> is the “simple” category, but Editorer given a special treatment to it in order to make their life better.

http://msdn.microsoft.com/en-us/library/bb384062.aspx” rel=“noreferer”> 收集初始剂。 您需要实施<条码>IE 计数<T>和Add方法。

It works thanks to collection initializers which basically require the collection to implement an Add method and that will do the work for you.

收集初始器的另一个冷却点是,你可以多载<代码>。 添加方法,你可以把所有方法都用同一个初始器!! 例如,这项工作:

public class MyCollection<T> : IEnumerable<T>
{
    public void Add(T item, int number)
    {

    }
    public void Add(T item, string text) 
    {

    }
    public bool Add(T item) //return type could be anything
    {

    }
}

var myCollection = new MyCollection<bool> 
{
    true,
    { false, 0 },
    { true, "" },
    false
};

它指正确的超载。 此外,它只考虑使用“<代码>Add”的方法,回归类型可能是什么。

The array like syntax is being turned in a series of Add() calls.

在更令人感兴趣的例子中看到这一点,我认为以下法典,在C#中,我做了两个令人感兴趣的事情,最初是非法的,在C#, 1中确定了一种只读的财产,2)列出了一个像初始者这样的阵列清单。

public class MyClass
{   
    public MyClass()
    {   
        _list = new List<string>();
    }
    private IList<string> _list;
    public IList<string> MyList 
    { 
        get
        { 
            return _list;
        }
    }
}
//In some other method
var sample = new MyClass
{
    MyList = {"a", "b"}
};

该守则将完美地运作,尽管1) 我的手法只读,2)我列出了一个有阵容初始剂的清单。

之所以进行这项工作,是因为在作为物体倾斜者一部分的法典中,汇编者总是将任何<代码>{><>>>/代码(如辛塔x)转至一系列<代码>Add(<>)的电话,这些电话即使是在读写领域也是完全合法的。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签