在 C# 中初始化 Generic.List

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/751990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:47:45  来源:igfitidea点击:

Initializing a Generic.List in C#

c#.netgenericsconstructor

提问by Anthony D

In C#, I can initialize a list using the following syntax.

在 C# 中,我可以使用以下语法初始化列表。

List<int> intList= new List<int>() { 1, 2, 3 };

I would like to know how that {}syntax works, and if it has a name. There is a constructor that takes an IEnumerable, you could call that.

我想知道该{}语法是如何工作的,以及它是否有名称。有一个带有 的构造函数IEnumerable,您可以调用它。

List<int> intList= new List<int>(new int[]{ 1, 2, 3 });

That seems more "standard". When I deconstruct the default constructor for the List I only see

这似乎更“标准”。当我解构 List 的默认构造函数时,我只看到

this._items = Array.Empty;

I would like to be able to do this.

我希望能够做到这一点。

CustomClass abc = new CustomClass() {1, 2, 3};

And be able to use the 1, 2, 3list. How does this work?

并且能够使用1, 2, 3列表。这是如何运作的?

Update

更新

Jon Skeet answered

乔恩斯基特回答

It's calling the parameterless constructor, and then calling Add:

它调用无参数构造函数,然后调用 Add:

> List<int> tmp = new List<int>();
> tmp.Add(1); tmp.Add(2); tmp.Add(3);
> List<int> intList = tmp;

I understand what is does. I want to know how. How does that syntax know to call the Add method?

我明白是做什么的。我想知道怎么做。该语法如何知道调用 Add 方法?

Update

更新

I know, how cliche to accept a Jon Skeet answer. But, the example with the strings and ints is awesome. Also a very helpful MSDN page is:

我知道,接受 Jon Skeet 的回答是多么陈词滥调。但是,带有字符串和整数的示例很棒。还有一个非常有用的 MSDN 页面是:

采纳答案by Jon Skeet

This is called a collection initializer. It's calling the parameterless constructor, and then calling Add:

这称为集合初始值设定项。它调用无参数构造函数,然后调用 Add:

List<int> tmp = new List<int>();
tmp.Add(1);
tmp.Add(2);
tmp.Add(3);
List<int> intList = tmp;

The requirements for the type are:

对类型的要求是:

  • It implements IEnumerable
  • It has overloads of Addwhich are appropriate for the argument types you supply. You can supply multiple arguments in braces, in which case the compiler looks for an Addmethod with multiple parameters.
  • 它实现 IEnumerable
  • 它具有Add适合您提供的参数类型的重载。您可以在大括号中提供多个参数,在这种情况下,编译器会查找Add具有多个参数的方法。

For example:

例如:

public class DummyCollection : IEnumerable
{
    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new InvalidOperationException("Not a real collection!");
    }

    public void Add(string x)
    {
        Console.WriteLine("Called Add(string)");
    }

    public void Add(int x, int y)
    {
        Console.WriteLine("Called Add(int, int)");
    }
}

You can then use:

然后您可以使用:

DummyCollection foo = new DummyCollection
{
    "Hi",
    "There",
    { 1, 2 }
};

(Of course, normally you'd want your collection to implement IEnumerableproperly...)

(当然,通常你会希望你的收藏IEnumerable正确实施......)

回答by Matt Grande

I believe it's a shortcut to the .Add method. I've never tried to override it, though, so I don't know if it's possible.

我相信这是 .Add 方法的快捷方式。不过,我从未尝试过覆盖它,所以我不知道是否可能。

回答by Cornel

Read Object and Collection Initializers (C# Programming Guide). Basically you could this with every custom type that is a list (implements IEnumerable).

阅读对象和集合初始值设定项(C# 编程指南)。基本上,您可以使用列表形式的每个自定义类型(实现 IEnumerable)。

回答by Jhonny D. Cano -Leftware-

As far as I'm concerned, the addition of items via object initialization searches a method Add. So, as List<int> will have void Add(int), it will work.

就我而言,通过对象初始化添加项目会搜索方法 Add。因此,由于 List<int> 将具有 void Add(int),因此它会起作用。

To use it in your class, just add

要在您的课程中使用它,只需添加

class CustomClass { 
   public void Add(int num) {
      // Your code here
   }
}

Your class should implement IEnumerable, as Hallgrim pointed out.

正如 Hallgrim 指出的那样,您的课程应该实现 IEnumerable。

回答by mqp

They're called collection initializers(also see here), and the way they work is by looking for an Add()method that can do their bidding. It calls Add()for each of the integers you have in your curly braces.

它们被称为集合初始值设定项(也请参见此处),它们的工作方式是寻找一种Add()可以进行竞价的方法。它调用Add()花括号中的每个整数。

The search for the Add()method is pure compiler magic. It's hardcoded to find a method of that name.

Add()方法的搜索是纯粹的编译器魔法。找到具有该名称的方法是硬编码的。

回答by JaredPar

The name you're loooking for is "Collection Initializer". It works under the hood by looking for a method named Add on the collection type and calling it for every value that you specify.

您正在寻找的名称是“集合初始值设定项”。它通过在集合类型上查找名为 Add 的方法并为您指定的每个值调用它来在幕后工作。

More details: Object and Collection Initializers (C# Programming Guide)

更多详细信息:对象和集合初始值设定项(C# 编程指南)

回答by Alexander Kahoun

It's actually using the .Addmethod. Meaning it's calling .Addfor each item in the brackets inside of the constructor.

它实际上是在使用该.Add方法。这意味着它正在调用.Add构造函数内括号中的每个项目。