.ToString()方法如何工作? [英] How does the .ToString() method work?
问题描述
有时,当我调用一个类的 .ToString()
方法时,它返回该类的完全限定名称。但是对于某些类/结构(例如 Int32
),它将返回与对象相对应的字符串(整数值)。这是否意味着 Int32
类将覆盖 ToString()
方法,而返回完全限定名称的类将不覆盖它,而是只调用base( Object
's) ToString()
方法? Object.ToString()
实现只是返回类的完全限定名称吗?
Sometimes when I call a class's .ToString()
method, it returns the fully qualified name of the class. But for some class's/struct's (like Int32
) it returns a string correspoding to the object (value of the integer). Does this mean the Int32
class overrides the ToString()
method, and classes that return fully qualified names don't override it, but instead just call base's (Object
's) ToString()
method? Does the Object.ToString()
implementation just return the class's fully qualified name?
推荐答案
有时,当我调用
ToString
方法时,它返回接收到调用的对象的运行时类型的全限定名。 / p>
Sometimes when I call the
ToString
method it returns the fully qualified name of the runtime type of the object that received the call.
正确。
但是对于某些类型,例如
System.Int32
,ToString
返回转换为字符串的接收者的值。
But for some types, such as
System.Int32
,ToString
returns the value of the receiver converted to a string.
正确。
System.Int32
结构是否覆盖ToString
方法?
是。
是否使用其他类型的
ToString
方法返回完全限定的类型类型名称 not 是否覆盖ToString
?
Do other types whose
ToString
methods return the fully-qualified type name not overrideToString
?
可能是这样,是的。当然,他们可以重写该方法,并让重写方法执行与基类方法完全相同的操作,但这将毫无意义。
That is probably the case, yes. Of course, they could override the method and have the overriding method do exactly the same thing as the base class method, but that would be a bit pointless.
因此,在这种情况下,调用
ToString
只会调用System.Object
实现。 > ToString ,它返回完全限定的名称吗?
So in those cases, calling
ToString
just calls theSystem.Object
implementation ofToString
, which returns fully qualified name?
正确。
您似乎对这是如何工作有扎实的了解。我唯一的更正是要注意 System.Int32
是 struct ,而不是 class 。
You seem to have a solid grasp of how this works. My only correction would be to note that System.Int32
is a struct, not a class.
这篇关于.ToString()方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!