Как работает typeof(T)?
От: catbert  
Дата: 29.06.10 08:57
Оценка:
Код:

    class Program
    {
        static void Main(string[] args)
        {
            Test<string>();
            Test<Program>();
            Console.ReadLine();
        }

        static void Test<T>()
        {
            Console.WriteLine(typeof(T).Name);
        }
    }

// Output:
    String
    Program


работает верно. Но ведь для всех reference-типов генерируется один метод Test. Откуда CLR берет результат для typeof(T)?
Re: Как работает typeof(T)?
От: perekrestov Украина  
Дата: 29.06.10 09:09
Оценка:
Здравствуйте, catbert, Вы писали:

C>
C>        static void Main(string[] args)
C>        {
C>            Test<string>();
C>            Test<Program>();
C>            Console.ReadLine();
C>        }

C>        static void Test<T>()
C>        {
C>            Console.WriteLine(typeof(T).Name);
C>        }
C>


C>работает верно. Но ведь для всех reference-типов генерируется один метод Test. Откуда CLR берет результат для typeof(T)?


Если я не ошибаюсь, то в рантайме JIT скомпилирует, в вашем случае, метод Test 2 раза.
1. Test<string>()
2. Test<Program>()

Т.е. скомпелированные ф-ции будут находится по двум разным адресам.
Re[2]: Как работает typeof(T)?
От: TK Лес кывт.рф
Дата: 29.06.10 10:30
Оценка: +1
Здравствуйте, perekrestov, Вы писали:

P>Если я не ошибаюсь, то в рантайме JIT скомпилирует, в вашем случае, метод Test 2 раза.

P>1. Test<string>()
P>2. Test<Program>()

P>Т.е. скомпелированные ф-ции будут находится по двум разным адресам.


Не совсем. если Program это наследник object то, метод будет один. просто, у него будет дополнительный скрытый параметр с generic типом.
Если у Вас нет паранойи, то это еще не значит, что они за Вами не следят.
Re[3]: Как работает typeof(T)?
От: perekrestov Украина  
Дата: 29.06.10 13:02
Оценка:
Здравствуйте, TK, Вы писали:


TK>Не совсем. если Program это наследник object то, метод будет один. просто, у него будет дополнительный скрытый параметр с generic типом.


When a method that uses generic type parameters is JIT-compiled, the CLR takes the method’s
IL, substitutes the specified type arguments, and then creates native code that is specific
to that method operating on the specified data types. This is exactly what you want and is
one of the main features of generics. However, there is a downside to this: the CLR keeps
generating native code for every method/type combination. This is referred to as code
explosion. This can end up increasing the application’s working set substantially, thereby
hurting performance.



The CLR has another optimization: the CLR considers all reference type arguments to be
identical, and so again, the code can be shared. For example, the code compiled by the CLR
for List<String>’s methods can be used for List<Stream>’s methods, since String and
Stream are both reference types. In fact, for any reference type, the same code will be used.



But if any type argument is a value type, the CLR must produce native code specifically for
that value type. The reason is because value types can vary in size. And even if two value
types are the same size (such as Int32 and UInt32, which are both 32 bits), the CLR still can’t
share the code because different native CPU instructions can be used to manipulate these
values.


Т.е, фактически, то что вы сказали, является результатом оптимизации для reference типов?
Re[4]: Как работает typeof(T)?
От: hardcase Пират http://nemerle.org
Дата: 29.06.10 13:10
Оценка:
Здравствуйте, perekrestov, Вы писали:

P>Т.е, фактически, то что вы сказали, является результатом оптимизации для reference типов?


Да. Незачем порождать для каждого ссылочного типа свой машинный код, так как он будет идентичен.
/* иЗвиНите зА неРовнЫй поЧерК */
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.