.NET SqlDataReader Item[] 与 GetString(GetOrdinal())?

标签 .net

使用SqlDataReader类,以下之间的功能差异(如果有)是什么:

(string) dataReader["MyFieldName"];

dataReader.GetString(dataReader.GetOrdinal("MyFieldName"));

最佳答案

抛开选角问题不谈,对于单一的召唤来说,不存在任何问题。索引器将调用 DbDataReader.GetOrdinal然后调用适当的 Get 方法来获取值(请注意,使用序号调用 Get 方法比使用带有字段名称的索引器更快) .

但是,这每次都会导致序数的查找。如果您以只进、只读的方式迭代多个记录(这正是 DbDataReader 实例的目的),那么您可以减少此查找的开销只需一次即可。

你可以这样做:

// Move to the first record.  If no records, get out.
if (!dataReader.Read()) return;

// Before the loop.  Can do this for any other fields being
// accessed in the loop as well.
int myFieldNameOrdinal = dataReader.GetOrdinal("MyFieldName");

// Process the records.  Remember, already on the first record, so
// use do/while here.
do
{
    // Do something with your field.
    Console.WriteLine(dataReader.GetString(myFieldNameOrdinal));
} while (dataReader.Read());

关于.NET SqlDataReader Item[] 与 GetString(GetOrdinal())?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6020117/

相关文章:

c# 将 3 个集合列表合并为一个列表

c# - Microsoft.ExceptionMessageBox 不是 "found"

c# - 调用 NamedPipeServerStream.SetAccessControl 时为 "Attempted to perform an unauthorized operation"

c# - WPF设计问题

c# - 在计算机休眠或 sleep 后恢复后,在 WPF 中使用什么事件来更新应用程序?

c# - 在大二进制文件中搜索字符串

c# - 从不同的程序集动态加载类(具有自定义行为)?

c# - 'real'语句存在的 "GOTO"目的是性能提升吗?

c# - Json.NET 不能仅使用隐式运算符自动处理值类型吗?

c# - 为什么我应该使用 continue 而不是空的 if 语句?