开发者

Why does a generic type in .NET has one entry in the TypeDef and another open type entry in TypeSpec?

Why does a generic type in .NET has on开发者_如何学Ce entry in the TypeDef and another open type entry in TypeSpec?

Was it simply to extended TypeDef with a signature when generics were added to .NET?


Let's have a look at those two different types:

public class Foo<TFoo> {}

public class Fighter {}

For those two definitions, and just like any other type, there will be an entry in the TypeDef table. In this case, there also will be an entry in the GenericParam table linking Foo to TFoo.

Now, most of the time, when using Foo, you won't use its definition directly, because it's not very interesting, you'll want to use an instantiation of Foo. So if you write:

new Foo<string> ();

There will be an entry in the TypeSpec table, specifying that you're using the type Foo with one generic argument: string. It's the same thing if you write:

public class Bar<TBar> {
    public Foo<TBar> Foo;
}

The compiler will also have to create TypeSpec entry, specifying that you're using the type Foo with one generic argument: TBar. You can consider TypeSpec as a specialization of a type, but they're not particular to generic instances. If you write:

var type = typeof (Fighter[,]);

You'll also find a entry in the TypeSpec table, to compose a rectangular array of Fighter. But if you write:

var type = typeof (Foo<>);

The definition of Foo which will be used, it's not instantiated: no TypeSpec entry for this usage. On the other hand, if you write:

var type = typeof (Foo<string>);

The same TypeSpec we talked about earlier will be used here.

To answer your last question, in this particular case, it's not to extend TypeDef to add generic informations: it's about using the standard tables to support new type constructs (TypeSpec).

On the other hand, some other tables were created to deal with new generic constructs, such as GenericParam, to support the definition of a generic parameter like TFoo, GenericParamConstraints to add constraints information to a generic parameter, and MethodSpec, which is to Method what TypeSpec is to TypeDef: a way to use a specialized method from a method definition. Also method signatures were modifyied to be able to support the generic arity of a method.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜