其中更有效的是Cstr(value)或value.ToString() [英] Which is more efficient Cstr(value) or value.ToString()

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

问题描述

我想知道哪个更有效率,使用CStr()或object.toString()。
我问这是因为我虽然所有的CStr()做的是调用.ToString()方法对它正在处理的对象。

I am wondering which is more efficient, using CStr() or object.toString(). The reason I ask this is because I though all that CStr() done was to invoke the .ToString() method on the object it was dealing with.

但是当最近使用没有任何类型约束的通用方法时,我不得不使用object.ToString()而不是CStr(object),下面是一个例子来说明这个问题。

But when recently using a generic method without any type constraints I had to use object.ToString() instead of CStr(object), the following is purely an example to illustrate the issue.

Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
    Return value.ToString
End Function

按预期编译,但下面没有使用CStr()。它给出了类型ID_TYPE的编译错误值无法转换为字符串。但是它显然可以使用.ToString()

Compiled as expected, but the following did not using CStr(). It gave an compilation error value of type ID_TYPE cannot be converted to string. But it obviously can using .ToString()

Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
    Return CStr(value)
End Function


推荐答案

这里(couldn 't说它更好):

From here (couldn't say it any better):


CStr是一个关键字,而ToString是
a函数(方法)。 CStr编译
inline并且它根据传递的对象的类型创建依赖于
的代码。它是
主要是为人们习惯了
从以前的VB版本。 I
没有在.Net中使用CStr
(因为它在
中并不明显,在这种情况下它也不是
非常好的文档)。

CStr is a keyword, whereas ToString is a function (method). CStr is compiled inline and it creates code depending on the type of the passed object. It's mainly there for people being used to it from previous VB versions. I haven't used CStr in .Net anymore (because it's not obvious what it does in which situations and it's also not very well documented).

这个差别取决于你使用的
ToString函数。每个类型
可以有自己的实现。

The difference depends on which ToString function you use. Every type can have it's own implementation.

这篇关于其中更有效的是Cstr(value)或value.ToString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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