我想知道哪个更有效率,使用CStr()或object.toString().
我问这个的原因是因为我尽管所有的CStr()完成是调用它所处理的对象上的.ToString()方法.
我问这个的原因是因为我尽管所有的CStr()完成是调用它所处理的对象上的.ToString()方法.
但是当最近使用没有任何类型约束的泛型方法时,我不得不使用object.ToString()而不是CStr(object),以下仅仅是一个例子来说明问题.
Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String Return value.ToString End Function
按预期编译,但以下没有使用CStr().它给出了类型为ID_TYPE的编译错误值不能转换为字符串.但它显然可以使用.ToString()
Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String Return CStr(value) End Function
从
here(不能说更好):
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).The difference depends on which ToString function you use. Every type can have it’s own implementation.