Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Where are generic methods stored?

I've read some information about generics in .ΝΕΤ and noticed one interesting thing.

For example, if I have a generic class:

class Foo<T> 
{ 
    public static int Counter; 
}

Console.WriteLine(++Foo<int>.Counter); //1
Console.WriteLine(++Foo<string>.Counter); //1

Two classes Foo<int> and Foo<string> are different at runtime. But what about case when non-generic class having generic method?

class Foo 
{
    public void Bar<T>()
    {
    }
}

It's obvious that there's only one Foo class. But what about method Bar? All the generic classes and methods are closed at runtime with parameters they used with. Does it mean that class Foo has many implementations of Bar and where the information about this method stored in memory?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As opposed to C++ templates, .NET generics are evaluated in runtime, not at compile-time. Semantically, if you instantiate the generic class with different type parameters, those will behave as if it were two different classes, but under the hood, there is only one class in the compiled IL (intermediate language) code.

Generic types

The difference between different instantiatons of the same generic type becomes apparent when you use Reflection: typeof(YourClass<int>) will not be the same as typeof(YourClass<string>). These are called constructed generic types. There also exists a typeof(YourClass<>) which represents the generic type definition. Here are some further tips on dealing with generics via Reflection.

When you instantiate a constructed generic class, the runtime generates a specialized class on the fly. There are subtle differences between how it works with value and reference types.

  • The compiler will only generate a single generic type into the assembly.
  • The runtime creates a separate version of your generic class for each value type you use it with.
  • The runtime allocates a separate set of static fields for each type parameter of the generic class.
  • Because reference types have the same size, the runtime can reuse the specialized version it generated the first time you used it with a reference type.

Generic methods

For generic methods, the principles are the same.

  • The compiler only generates one generic method, which is the generic method definition.
  • In runtime, each different specialization of the method is treated as a different method of the same class.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...