CStr() Str() .ToString() [英] CStr() Str() .ToString()

查看:23
本文介绍了CStr() Str() .ToString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道,函数 CStr()Str() 以及 .ToString() 之间究竟有什么区别>?使用下面提供的代码,这三者有什么区别?

I just want to know, what exactly the difference between the functions CStr() and Str() and also the .ToString()? With the code provided below, what's the difference between the three?

Label1.Text = CStr(Int(Rnd() * 10))

Label1.Text = Str(Int(Rnd() * 10))

Label1.Text = Int(Rnd() * 10).ToString

当我使用这个条件时

If Label1.Text = "7" Then
     'Some code here
End If

...Str() 函数在这里不起作用.它有什么不同?提前致谢:))

...the Str() function didn't work here. What difference did it make? thanks in advance :))

推荐答案

ToString 将在特定实例上调用 .ToString() 函数.实际上,这意味着如果对象在问题是Nothing.但是,您可以自己实现 .ToString()类来获取对象的有用字符串表示,而CType/CStr 仅适用于内置类和接口.

ToString will call the .ToString() function on a particular instance. In practice, this means that it will throw an exception if the object in question is Nothing. However, you can implement .ToString() in your own classes to get a useful string representation of your object, whereas CType/CStr only work with built-in classes and interfaces.

CStrCType(expression, String) 完全等效(我不是确定另一张海报从哪里得到 CStr 更快的想法).但他们不是真正的函数,它们是编译器指令,会发出非常不同的代码取决于表达式的声明.多数情况在这种情况下,这些指令会调用一堆内部 VB 代码,这些代码试图从表达式中得到一个合理的字符串.

CStr and CType(expression, String) are exactly equivalent (I'm not sure where the other poster got the idea that CStr is faster). But they aren't really functions, they're compiler directives that will emit very different code depending on the declaration of expression. In most cases, these directives call a bunch of internal VB code that tries to get a reasonable string out of expression.

DirectCast(expression, String) 假设问题确实是一个 String 并且只是转换它.这是最快的这些选项,但如果 expression 是任何内容,则会抛出异常不同于 String.

DirectCast(expression, String) assumes that the expression in question really is a String and just casts it. It's the fastest of all these options, but will throw an exception if expression is anything other than a String.

这篇关于CStr() Str() .ToString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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