在与一位同事谈论C#时,他向我展示了一些C#代码,我必须预测其输出。一开始这看起来很简单,但事实并非如此,我真的不明白为什么C#会这样。
代码:
public class A<T1>
{
public T1 a;
public class B<T2> : A<T2>
{
public T1 b;
public class C<T3> : B<T3>
{
public T1 c;
}
}
}
class Program
{
static void Main(string[] args)
{
A<int>.B<char>.C<bool> o = new A<int>.B<char>.C<bool>();
Console.WriteLine(o.a.GetType());
Console.WriteLine(o.b.GetType());
Console.WriteLine(o.c.GetType());
Console.ReadKey();
}
}
输出为:
System.Boolean
System.Char
System.Int32
如果我错了,请纠正我,但我理解o.a
是bool类型,因为C<T3>
继承自B<T3>
,而B<T2>
继承自A<T2>
。我还可以稍微理解o.c
是int类型,因为c
的类型是T1
,它从外部类(我认为)获得。
当我试图弄清楚为什么o.b
是char类型时,我的头几乎要爆炸了。有人能给我解释一下吗?
发布于 2013-01-09 22:57:24
好吧,我的第一个答案是错误的。嵌套很重要:
在o.b.GetType()
中,b是周围类的成员,该类被实例化为B<char>
,该类继承自A<char>
,从而使T1等于char。不太清楚的是(A_int.B_char.C_bool
的手动实例化):
public class A_bool
{
public bool a;
public class B_bool : A_bool
{
public bool b;
}
}
public class A_char
{
public char a;
public class B_bool : A_bool
{
public char b;
}
}
public class A_int
{
public int a;
public class B_char : A_char
{
public int b;
public class C_bool : A_char.B_bool
{
public int c;
}
}
}
这里的C_bool
也可以从A_bool.B_bool派生出来,对吧?但是因为我们嵌套在A_char
中,所以这是首选的。
https://stackoverflow.com/questions/14237621
复制相似问题