一道有趣的题,关于C#的多态

rainst大大论坛里出的,初看很简单,却掉进陷阱,贴出来以备忘

 1    class Program
 2    {
 3        static void Main(string[] args)
 4        {
 5
 6            var t = new C();
 7            t.Say();
 8            (t as B).Say();
 9            (t as A).Say();
10            Console.ReadLine();
11        }

12    }

13
14    class A
15    {
16        private int x = 1;
17        public virtual void Say()
18        {
19            Console.WriteLine(x.ToString());
20        }

21    }

22
23
24    class B : A
25    {
26        private int x = 2;
27        public new void Say()
28        {
29            Console.WriteLine(x.ToString());
30        }

31
32    }

33
34    class C : B
35    {
36    }

输出什么呢? 不许编译哦

把 t变量的声明改一下
A t = new C();

现在又输出啥呢?

更进一步,把class B改成
class B : A
    
{
        
private int x = 2;
       
        
public override void Say()
        
{
            Console.WriteLine(x.ToString());
        }


    }

现在呢?

posted on 2008-06-24 19:44  yyliuliang  阅读(551)  评论(5编辑  收藏  举报

导航