Since Int32 is a value type why does it inherit .ToString()?

别等时光非礼了梦想. 提交于 2019-12-05 16:57:45

问题


These are the docs about .ToString() that has prompted this question. They state:

Because Object is the base class of all reference types in the .NET Framework, this behavior [.ToString()] is inherited by reference types that do not override the ToString method.

Yet further on it goes to state:

For example, the base types such as Char, Int32, and String provide ToString implementations

However Int32 is a struct and hence must be a value type.

So what's going on here? Does Int32 implement it's very own .ToString() which has nothing to do with Object?


回答1:


Int32 is a struct and therefore a value type. But:

System.Object
   System.ValueType
      System.Int32

Int32 derives from System.ValueType and this itself derives from System.Object. Et voilà...




回答2:


Yes, Int32 overrides ToString... although that's somewhat irrelevant here. All types inherit the members of object - you can always call ToString(), you can always call Equals etc. (ValueType overrides Equals and GetHashCode for you, although you should almost always override them further in structs to provide a more efficient implementation.)

Note that you can override the methods yourself very easily:

public struct Foo
{
    public override string ToString()
    {
        return "some dummy text";
    }
}

It's not clear which aspect is confusing you (there are quite a few different areas involved here). If you could clarify, we could address the specific issue.




回答3:


Perhaps you confusion arises from not realizing that value types inherit from Object? Here is the inheritance graph of System.Object, System.ValueType, System.Int32 and MyNamespace.Customer which is supposed to be a class of you own making. I was lazy and didn't write all the public methods and interfaces of Int32.

ToString is declared in Object but is overriden both in ValueType and in Int32.




回答4:


The docs are wrong. Both reference and value types inherit that behavior from object (but do remember that not everything in .NET is a class that derives from object).

All (most?) core value types override ToString() to return something more sensible than the class name.




回答5:


I think the short answer to your question is that value types inherit from System.ValueType and that in turn inherits from object.




回答6:


Every struct have inheritance from System.ValueType class (not allowed) which is done solely by the compiler. All struct have methods from ValueType base class which is inherited from Object class makes us have access to ToString() and all others.

Even though ValueType is inherited from Object class but it has special implementation of the overrides.



来源:https://stackoverflow.com/questions/8152761/since-int32-is-a-value-type-why-does-it-inherit-tostring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!