日期:2014-05-17  浏览次数:20776 次

架构设计中关于类型转换(object<--->List),会有什么损失。
本帖最后由 toploveall 于 2013-10-19 18:24:11 编辑
直接上代码

     //父类
    public class Base
    {
        public virtual object GetList()
        {
            return null;
        }
    }
    
    //子类A
    public class A : Base
    {
        public override object GetList()
        {
            //返回List<A>
            List<A> aList = new List<A>();
            return aList;//会不会自动转成Object类型
        }
    }
    //子类B
    public class B : Base
    {
        public override object GetList()
        {
            List<B> bList = new List<B>();
            return bList;//会不会转成Object类型
        }
    }

    //上下文
    public class Context
    {
        Base b;
        public Context(Base b)
        {
            this.b = b;
        }
        public object GetList()
        {
            return b.GetList();
        }
    }

   //客户端
    public class Client
    {
        public void Test()
        {
            Context ct = new Context(new A());
            List<A> aList = ct.GetList() as List<A>;//会不会有性能损失,数据会不会转出错了
            List<B> bList = new Context(new B()).GetList() as List<B>;
        }
    }



我的意图大家通过代码应该很清楚。
以上的代码,把object和List之间转来转去,会不会影响性能,数据会不会转丢掉。
如果哪位大侠有更好的建议,请指点。
架构设计