从 DataRow 获取值之间的区别
示例代码:
DataTable table = new DataTable();
// ...
// insert column to table
table.Columns.Add("name");
// ...
// insert value to table
foreach (DataRow row in table.Rows) {
row["name"];
row.Field<string>("name");
}
我的问题是:
- 使用
row["name"]
和row.Field
之间有区别吗?当然,第二种方式将值转换为某种类型,但是还有其他区别吗?("name") - 使用哪种方法更好?
Sample code:
DataTable table = new DataTable();
// ...
// insert column to table
table.Columns.Add("name");
// ...
// insert value to table
foreach (DataRow row in table.Rows) {
row["name"];
row.Field<string>("name");
}
My question is:
- Is there a difference between using
row["name"]
androw.Field<string>("name")
? Of course, the second way cast value to some type, but is there another difference? - Which method is better to use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅备注部分,其中描述了主要差异:
最后一段指出了一点,因为我经常看到数字以字符串形式存储在数据库中,因此在数据检索时需要将
varchar
转换为int
,因此在本例中使用DataColumn 更好,例如:DataRowExtensions.Field;方法 (DataRow, String)
首次出现在 .NET 3.5 中,它“提供对指定行中每个列值的强类型访问。Field 方法还支持可空类型。 ”Afaik,
row["name"]
返回object
,row.Field("name")
返回String< /代码>。
我们不应该比较苹果和梨,因此您应该问哪个更好:
row["name"].ToString()
与row.Field("name")
答案是:它们是相同的。
See Remarks section, main differences described there:
The last paragraph makes a point as I've often seen numbers stored as strings in database, therefore
varchar
toint
conversion would be required on data retrieval, so in this case using DataColumn is better, e.g.:DataRowExtensions.Field<T> Method (DataRow, String)
first appeared in .NET 3.5 and it "provides strongly-typed access to each of the column values in the specified row. The Field method also supports nullable types."Afaik,
row["name"]
returnsobject
,row.Field<string>("name")
returns aString
.We shouldn't be comparing apples and pears, hence you should be asking what's better:
row["name"].ToString()
vsrow.Field<string>("name")
and the answer is: they're same.
这取决于您的目的,但如果您查看两者的定义,可能会告诉您;
DataRow.Item 属性 (DataColumn)
row["name" ]
DataRowExtensions.Field 方法(DataRow, DataColumn)
row.Field("name")
It depends on your purpose but if you look at a definition of both that may tell you;
DataRow.Item Property (DataColumn)
row["name"]
DataRowExtensions.Field Method (DataRow, DataColumn)
row.Field<string>("name")