How should I cast in VB.NET?

前端 未结 7 558
再見小時候
再見小時候 2020-11-29 17:29

Are all of these equal? Under what circumstances should I choose each over the others?

  • var.ToString()

  • CStr(var)

  • CType(var,

7条回答
  •  粉色の甜心
    2020-11-29 18:25

    Cstr() is compiled inline for better performance.

    CType allows for casts between types if a conversion operator is defined

    ToString() Between base type and string throws an exception if conversion is not possible.

    TryParse() From String to base typeif possible otherwise returns false

    DirectCast used if the types are related via inheritance or share a common interface , will throw an exception if the cast is not possible, trycast will return nothing in this instance

提交回复
热议问题