51代码网ORACLEMYSQLSQL SERVER其它数据库java/jspasp/asp.netC/C++/VC++APP应用其它语言服务器应用
您现在的位置: 51代码网 >> C >> 文章正文

C#调用父类的属性索引返回了子类

更新时间:2015-9-20:  来源:51代码网

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace test
{
    public class Brother
    {
        public Brother()
        {
        }
        private int _age;
 
        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
        public Brother this[int index]
        {
            get
            {
                if (index == 0)
                {
                    return new SmallBro();
                }
                else
                {
                    return new BigBro();
                }
            }
 
        }
        public virtual void Talk()
        {
        }
    }
    public  class SmallBro : Brother
    {
        public override void Talk()
        {
            Console.Write("smallbrother age:"+Age.ToString());
        }
 
    }
    public class BigBro : Brother
    {
        public override void Talk()
        {
            Console.Write("bigbrother age:" + Age.ToString());
        }
    }
 
}

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
 
namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Brother b = new Brother();
            b.Age = 11;
            b[0].Talk();
 
 
            Console.Read();
        }
    }
}

class Program
    {
        static void Main(string[] args)
        {
            Brother b = new Brother();
            b.Age = 11;
            b.Child<SmallBro>().Talk();
            Console.ReadLine();
        }
    }
 
 
    public class Brother
    {
        public Brother()
        {
        }
        private int _age;
 
        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
 
 
        public T Child<T>() where T : Brother, new()
        {
            T obj = new T();
            obj._age = this._age;
            return obj;
 
        }
 
 
        public virtual void Talk()
        {
        }
    }
    public class SmallBro : Brother
    {
        public override void Talk()
        {
            Console.Write("smallbrother age:" + Age.ToString());
        }
 
    }
    public class BigBro : Brother
    {
        public override void Talk()
        {
            Console.Write("bigbrother age:" + Age.ToString());
        }
    }

以前我们说对于OO学习的比较差的人,总是以为子类对象中有一个对象实例是父类类型的,也就是以为 SmallBro 对象实例内部还有另外一个对象被实例为 Brother 类型的,由此造成了一堆诡异的想法。

现在我知道这种想法也不过是“小问题”,可以看成简单的“技术性问题”了。因为我真的没有想到,还有人会更离谱地以为父类对象内部要住着各种子类对象的各种实例?

你千万不要往下学习OO了。先把概念想明白。如果人家.net 中定义一个类型叫做Control,难道它要把未来的几千种控件都要先在 Control 类型中写一遍?而且要把将来由用户定义的各种Control也预先写一遍?这显然是本末倒置的。

赞助商链接
推荐文章
  • 此栏目下没有推荐文章
  • {
    设为首页 | 加入收藏 | 友情链接 | 网站地图 | 联系站长 |