(string)reader[0] 和 reader[0].ToString() 之间的区别
DataReader[0].ToString()
和 (string)DataReader[0]
之间有区别吗?
我的猜测是,如果数据库类型不是字符串类型,(string)DataReader[0]
可能会失败,其中 DataReader[0].ToString()
只会转换DB null 之外的任何内容到字符串。是这样吗?
哪个会更快?
Is there a difference between DataReader[0].ToString()
and (string)DataReader[0]
?
My guess is that (string)DataReader[0]
might fail if the database type isn't a string type, where DataReader[0].ToString()
would just convert anything outside of a DB null to a string. Is that the case?
Which would be faster?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这些都会向您介绍潜在的数据异常,IMO 从阅读器读取的最佳方式是:
var x = reader[0] as string
然后对于数字/布尔等,我总是使用可空类型,这样您就可以get
var y = reader[1] as int?
现在,如果您出于某种原因绝对反对可空值(我认为它们非常适合知道某些内容是否已设置)
int i = (reader[1] as int?).GetValueOrDefault()
Those both introduce you to potential data exceptions, IMO the optimal way to read from a reader is:
var x = reader[0] as string
Then for numbers / bools etc I always use nullable types so you can get
var y = reader[1] as int?
Now if you absolutely are as opposed to nullables for some reason (I think they're great for knowing whether something is or not set)
int i = (reader[1] as int?).GetValueOrDefault()
(string)DataReader[0] 正在进行类型转换。编译器将在编译时插入一些需要执行的指令集以执行转换,并在失败时抛出异常。
DataReader[0].tostring() 是在运行时解析的函数调用,没有异常。
如有错误,请专家指正。
(string)DataReader[0] is typecasting. The compiler will insert some set of instructions at compile time that needs to be executed in order to perform the conversion and throws an exception when it fails to do so.
DataReader[0].tostring() is function call which gets resolved at runtime and no exceptions.
Experts please correct me if I am wrong.
我知道现在评论这个问题已经太晚了,但我认为很多人对
(string)object
和object.ToString()
有类似的疑问,这个问题是正确的发表评论的地方。当确定对象的类型是字符串时,最好进行
类型转换
,而不是调用方法.ToString()
。如果您查看ToString()
的代码:首先通过调用
GetType()
方法查找对象的类型,然后调用ToString()。
如果我们不确定
object
的类型,那么答案将是ToString()
而不是(string)
。如果您想查看 (string) 与 .ToString() 的性能基准,请点击链接:(string) 与 .ToString( )
I know its too late to comment on this question but I think many people have the similar doubt about
(string)object
andobject.ToString()
and this question is the correct place to comment on.When its sure that the type of object is string then its better to do a
typecasting
rather than calling a method.ToString()
. If you look into the code ofToString()
:Which is first finding the type of object by calling
GetType()
method then calling theToString()
of that type.If we are not sure about the type of
object
then the answer would be doToString()
instead of(string)
.If you wanted to see the benchmark of performance of (string) vs .ToString() then follow the link : (string) vs .ToString()