如何设置内联集合?
例如:
DataTable table = new DataTable()
{
Columns = new DataColumnCollection(
{
new DataColumn("col1"),
new DataColumn("col2")
})
});
For example:
DataTable table = new DataTable()
{
Columns = new DataColumnCollection(
{
new DataColumn("col1"),
new DataColumn("col2")
})
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您正在谈论 集合初始化程序
C# 3 中添加的功能。它是这样完成的:
这不会调用集合构造函数,它使用 DataTable 中已存在的集合。
这是 Columns.Add() 的简写,因此不需要 Columns 有 setter。
您与问题中的代码非常接近!
You are talking about the Collection Initialiser
feature added in C# 3. It is done like this:
This does not call a collection constructor, it uses the collection which already exists in the DataTable.
This is short-hand for Columns.Add(), so it doesn't require Columns to have a setter.
You were so close with the code in your question!
Columns
属性没有 setter,因此您只能修改它。怎么样:
如果您想使用 lambda 中的一条语句:
The
Columns
property does not have a setter so you can only modify it.How about this:
If you want to do with one statement in a lambda:
您可能需要删除
DataColumnCollection
的集合初始值设定项周围的括号,并删除不匹配的最终)
不过,这些都是语法问题。根本问题是 Columns 属性没有 setter,并且 DataColumnCollection 没有公共构造函数。
基本上,您必须实例化然后调用
.Columns.Add()
。如果这是您必须在代码中做很多事情的事情,您可以创建帮助器类来为您提供更友好的语法:
You probably need to remove the paretheses around that collection initializer for
DataColumnCollection
, and remove the unmatched, final)
Those are syntactical issues, though. The underlying problems are that the
Columns
property has no setter, and theDataColumnCollection
has no public constructor.Basically, you have to instantiate and then call
.Columns.Add()
.If this is something you have to do a lot in your code, you could create helper classes that would give you friendlier syntax:
这不起作用的原因有 2 个:
1)
Columns
属性是只读的2)
DataColumnCollection
类没有接受列集合来初始化它的构造函数。您能做的最好的事情就是在一行中创建表格并在另一行中添加列:
为了回答您的其他问题,IF
Columns
有一个设置器和IFDataColumnCollection
在其构造函数中接受列,语法为:There are 2 reasons why this won't work:
1) the
Columns
property is read-only2) the
DataColumnCollection
class does not have a constructor that accepts a collection of columns to initialize it.Best you can do is create the table in one line and add the columns in another:
To answer your other question, IF
Columns
had a setter and IFDataColumnCollection
accepted columns in its constructor the syntax would be:DataColumnCollection
类没有构造函数,因此您无法手动创建实例。编译器的错误消息应该是非常不言自明的,大致如下:您可以使用
Add()
方法将列添加到DataTable.Columns
集合中:The class
DataColumnCollection
has no constructor so you can't manually create an instance. The compiler's error message should be pretty self-explanatory, saying something along the lines of:You can add columns to the
DataTable.Columns
collection by using theAdd()
method:您不能使用该语法,因为 Columns 属性是只读的。我会使用加布建议的技术。
You can't use that syntax as the Columns property is readonly. I'd use the technique suggested by Gabe.