悬赏园豆:30
[已解决问题]
解决于 2008-07-25 13:53
interface ICounter<br> {<br> void Increment();<br> int Val<br> {<br> get;<br> }<br> }<br><br> struct Counter : ICounter<br> {<br> private int i;<br> public void Increment()<br> {<br> Console.WriteLine("改变前I:" + i.ToString());<br> ++i;<br> Console.WriteLine("改变后I:" + i.ToString());<br> }<br> public int Val<br> {<br> get<br> {<br> Console.WriteLine("取得I:" + i.ToString());<br> return i;<br> }<br> }<br> }<br><br> class C<T> where T : ICounter, new()<br> {<br> public void Fct()<br> {<br> T t = new T();<br> t.Increment();<br> System.Console.WriteLine(t.Val.ToString());<br> t.Increment();<br> System.Console.WriteLine(t.Val.ToString());<br> (t as ICounter).Increment();<br> System.Console.WriteLine(t.Val.ToString());<br> }<br> }<br><br><br> class Program<br> {<br> static void Main(string[] args)<br> {<br> C<Counter> c = new C<Counter>();<br> c.Fct();<br> Console.ReadLine();<br><br> }<br> }<br><br>这是一段关于泛型的问题,打印结果是<br>1<br>2<br>2<br><br>可我打了CONSOLE查看得出,值已经改变为3,可为什么取到的值还是2<br><br>还有<br>以下是上面代码的IL一段<br> IL_0067: ldloca.s CS$0$0001<br> IL_0069: call instance string [mscorlib]System.Int32::ToString()<br> IL_006e: call void [mscorlib]System.Console::WriteLine(string)<br> IL_0073: nop<br> IL_0074: ldloc.0<br> IL_0075: box !T<br> IL_007a: callvirt instance void ConsoleApplication5.ICounter::Increment()<br> IL_007f: nop<br> IL_0080: ldloca.s t<br> IL_0082: constrained. !T<br> IL_0088: callvirt instance int32 ConsoleApplication5.ICounter::get_Val()<br> IL_008d: stloc.2<br> IL_008e: ldloca.s CS$0$0001<br> IL_0090: call instance string [mscorlib]System.Int32::ToString()<br> IL_0095: call void [mscorlib]System.Console::WriteLine(string)<br><br><br>不明白为什么T约束某接口而且是T是值类型时,在T的实例上调用接口成员会引发一次装箱操作<br><br>此参考c#与NET实战 ---346页的一个DEMO<br>