VB 的 CTYPE() 的正确 C# 转换对应项
下面是我将其移植到 C# 重写中的 VB 片段。我的问题是作业后的 receipt_date
是多少?它仍然是一个对象
还是一个字符串
?
Dim receipt_date As Object
receipt_date = CType(dr.Item("RECTDT"), String)
这是正确的 C# 对应项吗?
object receipt_date;
receipt_date = dr["RECTDT"].ToString();
这两个执行后,VB 版本的 receipt_date
是否等于 C# 版本?如果不是,我需要做什么才能做到这一点?谢谢
The below is a snippet from VB that I am porting to a C# rewrite. My question is what is receipt_date
after the assignment? Is it still an object
or is it a string
?
Dim receipt_date As Object
receipt_date = CType(dr.Item("RECTDT"), String)
Would this be the correct C# counterpart?
object receipt_date;
receipt_date = dr["RECTDT"].ToString();
After both of these execute would the VB version, receipt_date
be equal to the C# version? If not, what do I need to do to make it so? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您最终会得到相同的结果。它在语义上与 VB 版本不同(您显式调用
ToString()
而不是使用CType
,这大致相当于 C# 中的强制转换),但功能相同。它也更安全,因为在数据库中转换 null 值(在运行时为DBNull
)会引发异常。不过,为了全面起见,实际的 C# 对应内容是这样的:
不过,作为风格的一点,尽量避免隐式类型(即使用
var
关键字而不是说string
或int
)用于简单类型。当类型将来可能发生变化(并且并不重要),或者类型很长和/或复杂并且var
使其更具可读性时,var
非常有用。在这种情况下,我建议:Yes, you would end up with the same result. It's semantically different from the VB version (you're calling
ToString()
explicitly instead of usingCType
, which is loosely equivalent to a cast in C#), but it's functionally identical. It's also safer, since casting a null value in the database (which would beDBNull
in the runtime) would throw an exception.Just for the sake of being comprehensive, though, the actual C# counterpart would be this:
As a point of style, though, try to avoid implicit typing (i.e., using the
var
keyword instead of sayingstring
orint
) for simple types.var
is useful when the type might change in the future (and isn't important), or if the type is long and/or complex andvar
makes it more readable. In this instance, I would suggest:VB 的
CType
关键字或多或少相当于Convert.ToString
,尽管不完全相同。因此,VB 中的以下内容...
...最好(或最接近)翻译为 C# 中的以下内容。
顺便说一下,
CType(..., String)
被编译为Microsoft.VisualBasic.CompilerServices.Conversions.ToString
。VB's
CType
keyword is more or less equivalent toConvert.ToString
though not exactly the same.So the following in VB...
...would be best (or most closely) translated to the following in C#.
By the way
CType(..., String)
gets compiled intoMicrosoft.VisualBasic.CompilerServices.Conversions.ToString
.