【发布时间】:2010-10-15 14:44:17
【问题描述】:
我有一些具有共同特性的类——我需要将它们放入基类中。
// This class needs to be designed
public class Base
{
// this function is no good because it returns object, and needs to return derived class
static object Create(byte[] data)
{
MemoryStream ms = new MemoryStream(data);
BinaryFormatter sf = new BinaryFormatter();
object result = sf.Deserialize(ms);
ms.Close();
return result;
}
public virtual byte[] Serialize()
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, this);
byte[] result = ms.ToArray();
ms.Close();
return result;
}
}
// for this class Create() must return Derived1
public Derived1 : Base
{
}
// for this class Create() must return Derived2
public Derived2 : Base
{
}
我需要能够像那样使用派生类工厂
Derived1 d1 = Derived1.Create(data1);
Derived2 d2 = Derived2.Create(data2);
请指教解决方案。模板没问题
更新
我更新了代码并展示了对象是如何序列化和反序列化的
【问题讨论】:
-
我认为您需要进一步解释,因为这没有意义。你打算如何在你的基类中创建“正确的”具体类?
-
Nix,我提供了 Create() 的实现
-
按照您的操作方式,您将需要使用类约束。见下文。