问题描述
我(显然是错误的)假设 Cstr(something)
等价于 something.ToString
.
我想将枚举类型作为字符串获取,这似乎取决于我使用的转换方法,我要么获取 enum
的索引或名称:
I (obviously incorrectly) had assumed that Cstr(something)
was equivalent to something.ToString
.
I wanted to get hold of an enumerated type as a string and it seems depending on which conversion method I use I either get the index of the enum
or the name:
Public Enum vehicleType
Car
Lorry
Bicycle
End Enum
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox("Index is " & _
CStr(vehicleType.Car) & _
".Name is " & _
vehicleType.Car.ToString)
End Sub
End Class
为什么这些到字符串的转换会返回 enum
类型的不同元素?
Why are these conversions to string returning different elements of the enum
type?
推荐答案
ToString
方法是一个标准的公共方法,它返回一个 String
.它是一种由基本 Object
类型定义为可重写的方法.因此,每个类都可以覆盖该方法以返回它想要的任何内容.类重写 ToString
方法以使其返回一个很好的人类可读的对象描述是很常见的.
The ToString
method is a standard public method that returns a String
. It is a method that is defined by the base Object
type as overrideable. Each class can, therefore, override that method to return anything that it wants. It is quite common for classes to override the ToString
method to make it return a nice human-readable description of the object.
CStr
是一个转换运算符.它是 CType(x, String)
的简写.与许多其他运算符一样,转换运算符可以被任何类覆盖.但是,通常情况下,您希望强制转换操作返回最接近原始对象实际值的表示,而不是描述性字符串.
CStr
, on the other hand, is a casting operator. It is shorthand for CType(x, String)
. The casting operator, like many other operators, can be overridden by any class. Normally, though, you want casting operations to return the closest representation of the actual value of the original object, rather than a descriptive string.
那么,您可能希望 ToString
返回与 CStr
不同的结果并不罕见.在枚举的情况下,每个成员本质上都是一个整数,因此枚举成员上的 CStr
与整数上的 CStr
工作方式相同.这就是你所期望的.但是,ToString
已被覆盖以返回更易读的值版本.这也是你所期望的.
It is not unusual then, that you may want ToString
to return a different result than CStr
. In the case of an enum, each member is essentially an Integer, so CStr
on an enum member works the same as CStr
on an integer. That is what you would expect. However, ToString
has been overridden to return the more human readable version of the value. That is also what you would expect.
下面是一个同时覆盖 CStr
和 ToString
的类的例子:
Here's an example of a class that overrides both CStr
and ToString
:
Public Class MyClass
Public Overrides Function ToString()
Return "Result from ToString"
End Function
Public Shared Widening Operator CType(ByVal p1 As MyClass) As String
Return "Result from cast to String"
End Operator
End Class
这篇关于处理 Enum 类型时 CStr() 与 .ToString 的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!