Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

c# - How does the .ToString() method work?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Sometimes when I call the ToString method it returns the fully qualified name of the runtime type of the object that received the call.

Correct.

But for some types, such as System.Int32, ToString returns the value of the receiver converted to a string.

Correct.

Does the System.Int32 struct override the ToString method?

Yes.

Do other types whose ToString methods return the fully-qualified type name not override ToString?

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.

So in those cases, calling ToString just calls the System.Object implementation of ToString, which returns fully qualified name?

Correct.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...