替换类中的类实例

本文关键字:实例 替换 | 更新日期: 2023-09-27 17:58:36

我有抽象类A,它可以在byte[]之间序列化自己。

另一个类C使用类型 T 进行参数化,该类型应该是或从A继承,并且具有无参数构造函数。 C需要在Tbyte[]之间双向转换。

Class C <T> where T : A, new() { ... }

问题是:如何从byte[]获得T

我不能使用A中的一些静态方法,因为我无法覆盖它。我不能调用T(byte[]),因为C#不允许这样做。

我发现的唯一方法是创建T实例并调用一些从A覆盖的方法,即:

byte[] bytes; // some byte table
T someT = new T();
T.LoadFromBytes(bytes);

我会工作,但在许多情况下,我只能从字节转换为新的T对象.有没有更好的解决方案或任何方法可以做到:

public class SomeTClass : A
{
    public SomeTClass(){...}
    public void LoadFromBytes(byte[] bytes)
    {
        SomeTClass newT = Sth(bytes); /* new instance of SomeTClass
                                         is created from bytes */
        this = newT; /* can't do this, but I need to replace
                        current instance with the new one */
    }
}

替换类中的类实例

我设法解决了这个问题,但我不喜欢我创建的代码。

这个想法是用 T 参数化类 A 并创建抽象方法,如果不从模板类型中使用抽象方法,它将是静态的:

public abstract class A <T>
{
    public abstract byte[] Serialize();
    public abstract T Deserialize(byte[]); //should be static
}

C 类有了新的规定:

public class C <T> where T : A <T>
{
    someMethod(...)
    {
        ...
        byte[] bytes; // some bytes
        T = new T().Deserialize(bytes); // should be T.Deserialize(bytes)
        ...
    }
}

以及一些T实现:

public class SomeTClass : A<SomeTClass>
{
    public SomeTClass Deserialize(byte[])
    {
        //deserialization code
    }
}

看看UpdateReference方法和反序列化实现。我认为您应该将反序列化方法设为farbic method.它应该将byte[]作为输入参数,并返回您需要类型的新实例。这是你想要的吗?

class C <T> where T : IA, new()
{
  public T Data { get; set; }
  .....
  public UpdateReference()
  {
    byte[] data = GetBytesFromSomewhere();
    Data = AImpl.Deserialize(data);
    Data.UserfulMethod();
    Data.AnotherUserfulMethod();
    data = GetBytesFromSomewhere();
    Data = AImpl.Deserialize(data)
    Data.UserfulMethod();
    Data.AnotherUserfulMethod();
  }
}
public interface IA
{
  public byte[] Serialize();
  public A Deserialize(byte[] data);
  public string UsefuleMethod1();
  public int AnotherUsefulMethod();
}
public class AImpl : IA
{
  public byte[] Serialize()
  {
    //Concrete implementation serialization
  }
  public static IA Deserialize(byte[] data)
  {
    //Concrete implementation deserialization
  }
}