Skip to main content
 首页 » 编程设计

c#之需要帮助设计类工厂

2024年02月24日18mq0036

我有一些具有共同特征的类 - 我需要将其放入基类中的类工厂。

// 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); 

请指教解决方案。模板没问题

更新

我更新了代码并展示了对象是如何序列化和反序列化的

请您参考如下方法:

public class Base<T> 
{ 
    public static T Create(byte[] data) 
    { 
        // create instance of T from data 
    } 
} 
 
public Derived1 : Base<Derived1> 
{ 
} 
 
public Derived2 : Base<Derived2> 
{ 
}