开发者

What exactly does a self-describing type in .Net mean?

Given this MSDN article, we learn that the Common Type System in .Net has this classification of reference types:

"Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types."

  1. So an array, for instance, is a self-describing type because 开发者_Go百科we can determine its type from its values?
  2. How?
  3. Is that it, or is there more to this definition?


A self-describing type is type that is described by metadata available about itself. The most common form are class types. There it's quite easy to show what self-describing means:

The type itself is described by the class definition. e.g. A customer class with a name, age and customerid. The pure data for an instance of this class would be something like:

8%3|*1C U S T O M E R

Only because the environment has the class description containing the metadata you really know that some of this data forms the id, age and name. And to identify the metadata the object content data is merged with a class id so the environment can match the class description with the metadata.

|Class metadata reference: Metadata for the customer class
| |Customer ID: Field 
| |  |Customer Age: Field
| |  ||Customer Name : Field
8%3|*1C U S T O M E R

For arrays it is similar: Array classes contain information about the number of entries as well as type information (see above) about the stored entries.


A self-describing type is a data type that provide information about themselves for the benefit of the garbage collector. Basically any type that has some form of Metadata e.g. an assembly, would be considered a self-describing type.


Maybe the best way to show how pointer types and interface types are not self-describing is with an example:

using System;

interface ISample { }
class CSample : ISample { }

class Program {
    static unsafe void Main(string[] args) {
        ISample itf = new CSample();
        var it = itf.GetType();
        Console.WriteLine(it.FullName);
        int value = 42;
        int* p = &value;
        var pt = p->GetType();
        Console.WriteLine(pt.FullName);
        Console.ReadLine();
    }
}

Output:

CSample 
System.Int32

In other words, objects declared as an interface type can only describe the class that implements them. Pointers can only describe the type of the object they point to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜