class Fruit
    { }
    class Apple : Fruit
    {
        public int i=1;
    }
    public class Mod
    {
        static void Main()
        {
            Fruit f = new Apple();
            Type t = f.GetType();
            Apple a=f;
            Console.WriteLine(a.i);
        }
    }想问的是 f 属于Fruit类型,但是用Apple来new,而且GetType 显示也是Apple
为什么Apple a=f;这样,却访问不了i呢? 还要强制转换为什么呢?
f到底是Apple 还是Fruit呢?如果是Fruit,怎么GetType又是Apple呢?
这个问题没搞懂.

解决方案 »

  1.   

    但为什么f.GetType(); 结果是Apple呢?
      

  2.   

    奇怪啊,以前都没注意这问题,Fruit f = new Apple();的f应该就是Fruit了,怎么输出是Apple?既然是Apple怎么还需要强制转换呢.....关注 啊,那个出来解释哈嘛
      

  3.   

    有人向外星人解释,男人是人类中的一种人(人类 人=new 男人()),男人有JJ一天外星人见到一女人时说,人,掏你JJ出来看看。...
    完毕.
      

  4.   

    如果你想访问Apple里的i的话,那你就要保证每个Fruit都有个i比如这样:abstract class  Fruit
    {
        public abstract int i { get;}
    }
    class Apple : Fruit
    {
        public override int i
        {
            get { return 1; }
        }
    }
    public class Mod
    {
        static void Main()
        {
            Fruit f = new Apple();
            Type t = f.GetType();
            Apple a = f;
            Console.WriteLine(a.i);
        }
    }
    告诉外星人,人类都有个脑袋。见谁都不会闹笑话。
    丫死人不算...完毕。
      

  5.   

        class Fruit
        { }
        class Apple : Fruit
        {
            public int i = 1;
        }
        public class Mod
        {
            static void Main()
            {
                Fruit f = new Apple();
                Type t = f.GetType();
                Apple a = (Apple)f;
                Console.WriteLine(a.i);
            }
        }
    强制类型转化一下就好了,C#它不知道你是那个儿子来代替父亲,所以他不会通过编译的