gpt4 book ai didi

c# - 从 DataRow 获取值(value)的区别

转载 作者:IT王子 更新时间:2023-10-29 04:44:16 26 4
gpt4 key购买 nike

示例代码:

    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<string>("name") ?当然,第二种方式将值转换为某种类型,但是还有其他区别吗?
  • 哪种方法更好用?

最佳答案

参见 Remarks section ,那里描述的主要区别:

The DataSet class represents null values with the Value instance of the DBNull class. A Language-Integrated Query (LINQ) expression that accessed a column with a null value would generate a InvalidCastException at run time. Additionally, DataSet does not support nullable types. The Field method provides support for accessing columns as nullable types. If the underlying value in the DataSet is Value, the returned nullable type will have a value of null.

If the value of the specified DataColumn is null and T is a reference type or nullable type, the return type will be null. The Field method will not return Value.

The Field method does not perform type conversions. If type conversion is required, you should first obtain the column value by using the Field method. The column value should then be converted to another type.

最后一段提出了一个观点,因为我经常看到数字在数据库中存储为字符串,因此 varcharint数据检索需要转换,因此在这种情况下使用 DataColumn 更好,例如:

int test = row.Field<int>("Test"); // InvalidCastException
int test = Convert.ToInt32(row["Test"]); // Works like a charm

DataRowExtensions.Field<T> Method (DataRow, String)首次出现在 .NET 3.5 中,它“提供对指定行中每个列值的强类型访问。Field 方法还支持可空类型。”

阿法克,row["name"]返回 object , row.Field<string>("name")返回 String .我们不应该比较苹果和梨,因此你应该问哪个更好:

row["name"].ToString()对比row.Field<string>("name")答案是:它们是一样的。

关于c# - 从 DataRow 获取值(value)的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7104675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com