Do interfaces derive from System.Object? C# spec says yes, Eric says no, reality says no

后端 未结 4 2157
时光取名叫无心
时光取名叫无心 2020-11-30 00:47

Question is simple and asked in the title.

C# 4.0 Specification says: (§4.2.2)

The object class type is the ultimate base class of all other

4条回答
  •  借酒劲吻你
    2020-11-30 01:00

    Interface types do not inherit from Object, but storage locations of interface types hold references to class-type objects which (if non-null) are guaranteed to inherit from System.Object.

    I think understanding what's going on will be easiest if one starts by examining the difference between value types and class types. Suppose I have a structure:

    public struct SimplePoint {public int x,y;}
    

    and I have two methods

    public doSomethingWithPoint(SimplePoint pt) ...
    public doSomethingWithObject(Object it) ...
    

    and cal each method:

    SimplePoint myPoint = ...;
    doSomethingWithPoint(myPoint);
    dosomethingWithObject(myPoint);
    

    The first call does not pass a thing that derives from Object. It instead passes the contents of all of SimplePoint's public and private fields. The second call needs a thing which derives from Object, so it generates a new heap object instance of type SimplePoint which contains all the public and private fields of the value-type SimplePoint, and loads all those fields with the corresponding values from myPoint, and passes a reference to that object.

    Note that the type SimplePoint actually describes two different kinds of things: a collection of fields (i.e. the value type) and a heap-object type. Which meaning is applicable depends upon the context where the type is used.

    Interface types have a similar wrinkle: when used as storage-location types, they specify that the storage location will hold an object reference. When used as a generic constraint, they say nothing about how the type will be stored. Thus, a storage location of an interface type will hold a reference to a heap object that genuinely does inherit from System.Object, but a variable of a type constrained to an interface might hold either a reference or a bunch of fields.

提交回复
热议问题