我有抽象类A,它可以将自身序列化到byte[].
另一个类使用类型进行C参数化,T该类型应该是或继承自A并具有无参数构造函数。需要在和C之间进行双向转换。Tbyte[]
Class C <T> where T : A, new() { ... }
问题是:如何T获得byte[]?
我不能使用来自 的一些静态方法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 */
}
}