我应该如何投资在VB.NET? [英] How should I cast in VB.NET?
本文介绍了我应该如何投资在VB.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这些都是平等的吗?
-
var.ToString()
-
CStr(var)
-
CType(var,String)
DirectCast(var,String)
EDIT: NotMyself … $ b的建议
$ b
- TryCast(var,String)
解决方案<
-
var。这些都略有不同, code>
ToString
()
将给你一个对象的字符串表示,而不管它是什么类型。如果var
不是字符串,请使用此方法。 -
CStr
(var)
是VB字符串转换操作符。我不是一个VB的家伙,所以我建议避免它,但它不是真的会伤害任何东西。我认为它基本上与CType
相同。 -
CType
(var,String)
将使用任何提供的转换运算符将给定类型转换为字符串。 -
DirectCast
(var,String)
- 将对象转换为字符串。如果你知道一个对象变量实际上是一个字符串,使用这个。这与C#中的(string)var
相同。 -
TryCast
(如@ NotMyself )就像DirectCast
,但它会返回Nothing
如果该变量不能转换为字符串,而不是抛出异常。这与C#中的var as string
相同。TryCast 页面也有很好的比较。
Are all of these equal? Under what circumstances should I choose each over the others?
var.ToString()
CStr(var)
CType(var, String)
DirectCast(var, String)
EDIT: Suggestion from NotMyself…
- TryCast(var, String)
解决方案
Those are all slightly different, and generally have an acceptable usage.
var.
ToString
()
is going to give you the string representation of an object, regardless of what type it is. Use this ifvar
is not a string already.CStr
(var)
is the VB string cast operator. I'm not a VB guy, so I would suggest avoiding it, but it's not really going to hurt anything. I think it is basically the same asCType
.CType
(var, String)
will convert the given type into a string, using any provided conversion operators.DirectCast
(var, String)
is used to up-cast an object into a string. If you know that an object variable is, in fact, a string, use this. This is the same as(string)var
in C#.TryCast
(as mentioned by @NotMyself) is likeDirectCast
, but it will returnNothing
if the variable can't be converted into a string, rather than throwing an exception. This is the same asvar as string
in C#. TheTryCast
page on MSDN has a good comparison, too.
这篇关于我应该如何投资在VB.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文