如何在声明的同一行中初始化 C# 列表。 (IEnumerable 字符串集合示例)
我正在编写我的测试代码,我不想写:
List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
我很想写
List<string> nameslist = new List<string>({"one", "two", "three"});
但是{“一”,“二”,“三”}不是“IEnumerable字符串集合”。如何使用 IEnumerable 字符串集合在一行中初始化它?
I am writing my testcode and I do not want wo write:
List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
I would love to write
List<string> nameslist = new List<string>({"one", "two", "three"});
However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
本质上语法是:
由编译器翻译为
Essentially the syntax is:
Which is translated by the compiler as
将代码更改为
或
Change the code to
or
只要去掉括号即可:
Just lose the parenthesis:
为那些想要使用 POCO 初始化列表的人发布此答案,因为这是搜索中弹出的第一件事,但所有答案仅适用于字符串类型列表。
您可以通过两种方式执行此操作,一种是通过 setter 赋值直接设置属性,或者通过创建一个接受参数并设置属性的构造函数来更简洁。
或者通过参数化构造函数
Posting this answer for folks wanting to initialize list with POCOs and also coz this is the first thing that pops up in search but all answers only for list of type string.
You can do this two ways one is directly setting the property by setter assignment or much cleaner by creating a constructor that takes in params and sets the properties.
OR by parameterized constructor
这是一种方法。
这是另一种方式。
字符串也是如此。
例如:
This is one way.
This is another way.
Same goes with strings.
Eg:
去掉括号:
Remove the parentheses:
这取决于您使用的 C# 版本,从 3.0 版本开始您可以使用...
It depends which version of C# you're using, from version 3.0 onwards you can use...
我认为这适用于 int、long 和 string 值。
I think this will work for int, long and string values.
C# 12 (.NET 8+) 的方式是:
虽然不使用
var
,但它需要知道类型,因为新的集合文字可用于任何类型的集合。来源:https://learn。 microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12#collection-expressions
C# 12 (.NET 8+) way is:
though don't use
var
with it, it needs to know the type since the new collection literals can be used for any kind of collection.Source: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12#collection-expressions