我应该如何投资在VB.NET? [英] How should I cast in VB.NET?

查看:141
本文介绍了我应该如何投资在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 if var 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 as CType.
  • 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 like DirectCast, but it will return Nothing if the variable can't be converted into a string, rather than throwing an exception. This is the same as var as string in C#. The TryCast page on MSDN has a good comparison, too.

这篇关于我应该如何投资在VB.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆