正确的C#转换为对应的VB的CTYPE() [英] Correct C# conversion counterpart for VB's CTYPE()
问题描述
以下是从VB,我移植到C#重写一个片段。我的问题是什么是 receipt_date
在转让之后?是不是仍然是一个对象
或者是一个字符串
?
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)
这会是正确的C#同行?
Would this be the correct C# counterpart?
object receipt_date;
receipt_date = dr["RECTDT"].ToString();
在这两种执行将在 VB 版本, receipt_date
等于 C#版本?如果没有,你有什么我需要做,使会这样呢?谢谢
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
推荐答案
是的,你最终会得到相同的结果。它,而不是使用VB的版本(你调用的ToString()
语义不同的明确 CTYPE
,这是松散相当于投在C#中),但它的功能相同。这也是比较安全的,因为在数据库中铸造一个空值(这将是的DBNull
在运行时)会抛出异常。
Yes, you would end up with the same result. It's semantically different from the VB version (you're calling ToString()
explicitly instead of using CType
, 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 be DBNull
in the runtime) would throw an exception.
贪图的是COM prehensive,不过,实际的C#对应的是这样的:
Just for the sake of being comprehensive, though, the actual C# counterpart would be this:
var receipt_date = (string)dr["RECTDT"];
作为一个点的风格,但是,尽量避免隐式类型(例如,使用称 VAR
关键字,而不是字符串
或 INT
)的简单类型。 VAR
当类型可能会在未来改变是很有用的(而且并不重要),或者如果类型是长期和/或复杂的变种
使其更具可读性。在这种情况下,我建议:
As a point of style, though, try to avoid implicit typing (i.e., using the var
keyword instead of saying string
or int
) 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 and var
makes it more readable. In this instance, I would suggest:
string receipt_date = (string)dr["RECTDT"];
这篇关于正确的C#转换为对应的VB的CTYPE()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!