110,539
社区成员
发帖
与我相关
我的任务
分享
//父类
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>;
}
}
//父类
public class Base<T>
{
public virtual List<T> GetList()
{
return null;
}
}
//子类A
public class A : Base<A>
{
public override List<A> GetList()
{
//返回List<A>
List<A> aList = new List<A>();
return aList;//会不会自动转成Object类型
}
}
//子类B
public class B : Base<B>
{
public override List<B> GetList()
{
List<B> bList = new List<B>();
return bList;//会不会转成Object类型
}
}
//上下文
public class Context<T>
{
Base<T> b;
public Context(Base<T> b)
{
this.b = b;
}
public List<T> GetList()
{
return b.GetList();
}
}
//客户端
public class Client
{
public void Test()
{
Context<A> ct = new Context<A>(new A());
List<A> aList = ct.GetList();
List<B> bList = new Context<B>(new B()).GetList();
}
}
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;
}
public object GetList()
{
return b.GetList();
}
}
public class Client
{
public void Test()
{
var aList = new Context(new DerivedA()).GetList();
var bList = new Context(new DerivedB()).GetList();
}
}