架构设计中关于类型转换(object<>List),会有什么损失。该如何处理
架构设计中关于类型转换(object<--->List),会有什么损失。
直接上代码
我的意图大家通过代码应该很清楚。
以上的代码,把object和List之间转来转去,会不会影响性能,数据会不会转丢掉。
如果哪位大侠有更好的建议,请指点。
------解决方案--------------------
直接上代码
//父类
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之间转来转去,会不会影响性能,数据会不会转丢掉。
如果哪位大侠有更好的建议,请指点。
架构设计
性能
------解决方案--------------------
public abstract class Base
{
public abstract IEnumerable<Base> GetList();
}
public class DerivedA : Base
{
public override IEnumerable<Base> GetList()
{
return new List<DerivedA>();
}
}
public class DerivedB : Base
{
public override IEnumerable<Base> GetList()
{
return new List<DerivedB>();
}
}
public class Context
{
Base b;
public Context(Base b)
{
this.b = b;