Correct C# conversion counterpart for VB's CTYPE()

旧城冷巷雨未停 提交于 2019-12-24 00:49:23

问题


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


回答1:


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.

Just for the sake of being comprehensive, though, the actual C# counterpart would be this:

var receipt_date = (string)dr["RECTDT"];

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"];



回答2:


VB's CType keyword is more or less equivalent to Convert.ToString though not exactly the same.

So the following in VB...

Dim receipt_date As Object 
receipt_date = CType(dr.Item("RECTDT"), String) 

...would be best (or most closely) translated to the following in C#.

object receipt_date;
receipt_date = Convert.ToString(dr.Item["RECTDT"]);

By the way CType(..., String) gets compiled into Microsoft.VisualBasic.CompilerServices.Conversions.ToString.



来源:https://stackoverflow.com/questions/3231049/correct-c-sharp-conversion-counterpart-for-vbs-ctype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!