铸造 SqlDataReaders
将 (int)reader[0]
替换为 reader.GetInt32(0)
有何优点? 我确信这样的铸造功能的存在是有原因的,但除了我自己避免铸造感觉更美观之外,我不确定这些原因是什么。
What are the advantages of replacing (int)reader[0]
with reader.GetInt32(0)
? I'm sure such casting functions are there for a reason, but other than it feeling more aesthetically pleasing to avoid the cast myself, I'm not sure what those reasons are.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在代码中......
在IL中
所以,IL是不同的,但我怀疑它们之间有任何明显的区别。 也许经过一百万次迭代后您会看到差异,但可能性不大。
In code....
In IL
So, the IL is different, but I doubt that there is any noticeable difference between them. Maybe after a million iterations you will see the difference, but not likely.
前者还可以接受列名作为字符串而不是索引,并尝试将列值转换为 int。 后者仅接受索引,不会执行转换。
The former can also accept the column name as a string rather than an index, and will attempt to cast the column value to an int. The latter only accepts the index and no casting will be performed.
reader[0] 返回一个 System.Object,(int)reader[0] 实际上正在执行从 Object 到 Int32 的转换。
如果调用 GetXXX(0) 方法,则不会执行任何转换。 因此,从流中检索的数据必须已经是该方法指定的类型。
如果检索到的数据类型不匹配或列具有 DBNull,则会抛出 InvalidCastException。
reader[0] returns an System.Object, (int)reader[0] is actually doing a cast from Object to Int32.
If you call GetXXX(0) methods, no conversions are performed. Therefore, the data retrieved from the stream must already be the type the method specified.
If the type of data retrieved doesn't match or the column has DBNull, it throws an InvalidCastException.