什么时候在C#中解析泛型类型? [英] When is the generic type resolved in c#?
问题描述
根据这个在stackoverflow上的回答, C#中的泛型类型在运行时解析。
我在这里错过了什么?
换句话说,是 T
解决在编译时或运行时?
更新:
基于Oded的回答,这个类型是一个封闭的具体类型(这意味着它会在编译时解析)
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b {
static void Main()
{
var t = new Test< int>();
}
}
public class Test< T>
{
}
MSIL具有相当于
class Program
{
static void Main()
{
var t = new Test ();
}
}
public class Test< int>
{
}
问题是这个问题不是很好。两个人声称有相反的东西:类型在运行时被解决,并且类型在编译时被解决。
由于它们相互矛盾,它们必须都意味着不同的解决。
我不知道类型被解决是什么意思。然而,我确实知道什么是重载分辨率。当要求解决不涉及 dynamic
的重载解析问题时,C#编译器确定在编译时调用的哪个重载 em>,基于关于泛型类型的编译时间信息。例如,如果你有:
static void Main()
{
var d = new d();
var p = new P< D>();
pN(d); //显示在类B
}
class B
{
public void M()//注意,不是虚拟
{
Console.WriteLine(在B类中);
class D:B
{
public new void M()// new,not overload
{
Console.WriteLine(在D类中);
}
}
class P< T>其中T:B
{
public void N(T t)
{
t.M();
$ / code $ / pre>
N $ c即使 P< T>
被实例化为,总是调用 BM
P< d取代;
。为什么?因为当 P .N $ c $>时,必须解决 tM
的含义的重载解析问题c>编译,那时编译器知道的最好的是 t
必须是 B
,所以它选择 BM
。
如果这不是解决的意思,那就澄清问题。
According to this answer at stackoverflow, the generic type in C# is resolved at runtime.
However, according to this answer, in C#, the generic type is resolved at compile time.
What am I missing here?
In other words, is the type T
resolved at compile time or run time?
Update:
Based on Oded's answer, In a case like this, where the type is a closed concrete type (which means it would be resolved at compile time)
class Program
{
static void Main()
{
var t = new Test<int>();
}
}
public class Test<T>
{
}
will the MSIL have the equivalent of
class Program
{
static void Main()
{
var t = new Test();
}
}
public class Test<int>
{
}
解决方案 The problem is that the question is not well-posed. Two people are claiming opposite things: that types are "resolved" at runtime and that types are "resolved" at compile time.
Since they are contradicting each other, they must both mean something different by "resolved".
I do not know what it means for a type to be "resolved". I do know however what overload resolution is. When asked to solve an overload resolution problem that does not involve dynamic
, the C# compiler determines which overload to call at compile time, based on the compile time information about the generic type. So for example, if you have:
static void Main()
{
var d = new D();
var p = new P<D>();
p.N(d);//Displays In class B
}
class B
{
public void M()// Note, not virtual
{
Console.WriteLine("In class B");
}
}
class D : B
{
public new void M()// new, not overload
{
Console.WriteLine("In class D");
}
}
class P<T> where T : B
{
public void N(T t)
{
t.M();
}
}
N
always calls B.M
even if P<T>
is instantiated as P<D>
. Why? Because the overload resolution problem that determines what the meaning of t.M
is must be solved when P<T>.N
is compiled, and at that time, the best the compiler knows is that t
must be B
, so it chooses B.M
.
If that's not what you mean by "resolved" then clarify the question.
这篇关于什么时候在C#中解析泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!