DataReader[i] 与 DataReader.GetValue(i) 与 DataReader.GetString(i)
它们
dataReader[i]
逻辑上等同于
dataReader.GetValue(i)
相同吗?它们有什么不同吗?是否存在一种情况比另一种更合适?
有记录不同:
- 获取位于指定索引处的列
- 返回指定字段的值。
但是当我使用它们时,它们都返回该字段的值。 “获得专栏”是什么意思? “返回字段的值”是什么意思?
Bonus Chatter:
当我打电话时:
reader[i];
reader.GetValue(i);
reader.GetString(i);
我每次都会收到一个String
Is
dataReader[i]
logically equivalent to
dataReader.GetValue(i)
Are they the same? Are they different? Is there a situation where one would be appropriate over the other?
There are documented differently:
- Gets the column located at the specified index
- Return the value of the specified field.
But when i use them they both return the value of the field. What does it mean to "get the column"? What does it mean to "return the value of a field"?
Bonus Chatter:
When I call:
reader[i];
reader.GetValue(i);
reader.GetString(i);
i get a String
each time
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最终,它取决于您所指的 System.Data.IDataReader 的特定实现,但我们假设您指的是 System.Data.SqlClient.SqlDataReader。
在本例中,
reader[i]
和reader.GetValue(i)
执行的操作完全相同。事实上,reader[i]
在内部调用reader.GetValue(i)
。 (您可以通过使用 ILSpy 等工具反汇编代码来看到这一点。)。这两个成员都返回当前行第i列的值,并且无论值的类型如何(返回类型为object
)都会成功返回。这两位成员的文档有点误导性,可以用更好的方式措辞。您可以在任何地方使用这些成员中的任何一个,只需选择您认为读起来更好的一个即可。而
reader.GetString(i)
专门设计用于以string
形式返回当前行第 i 列中包含的值。如果该列中的值不是字符串
,则会抛出InvalidCastException
。当您确定该值是string
并且string
是您要使用的类型时,请使用此方法。这将使您的代码更加简洁,因为您不必执行强制转换。在您的特定情况下,当前行的第 i 列中的值必须为
string
类型,这就是为什么所有三个成员的返回值相同的原因。如果编写正确,
System.Data.IDataReader
的其他实现应该具有相同的行为方式。Ultimately it depends on the particular implementation of
System.Data.IDataReader
you are referring to, but let's assume you meanSystem.Data.SqlClient.SqlDataReader
.In this case,
reader[i]
andreader.GetValue(i)
do exactly the same thing. In fact,reader[i]
internally callsreader.GetValue(i)
. (You can see this by disassembling the code using a tool like ILSpy.). Both these members return the value in the i-th column of the current row and will return successfully regardless of the type of the value (the return type isobject
). The documentation for both of these members is a little misleading and could be worded in a better way. You can use either of these members wherever you like, just pick the one which you feel reads better.Whereas
reader.GetString(i)
is specifically designed to return the value contained in the i-th column of the current row as astring
. If the value in that column is not astring
, anInvalidCastException
will be thrown. Use this method when you are sure that the value is astring
andstring
is the type that you want to work with. This will make your code more concise since you won't have to perform a cast.In your specific case, the value in the i-th column of the current row must be of type
string
, which is why the return value of all three members is identical.If written correctly, other implementations of
System.Data.IDataReader
should behave in the same way.