c#T的实例

Sve*_*exo 1 .net c# generics

我正在尝试创建一个genric代码来序列化和反序列化实现特定接口的任何对象.问题是我需要在调用.Deserialize()之前创建一个对象的实例,因为你不能在接口中使用静态函数.现在我的问题是如何制作T的实例?还是有更好的方法来实现我的目标?

public static class Serializer
{
    public static byte[] Serialize<T>(T Obj) where T : Data;
    public static T Deserialize<T>(byte[] Data) where T : Data
    {
        //Here I need to something like:  new T().Deserialize(Data);
    }
}
public interface Data
{
    public byte[] Serialize<T>(T obj);
    public T Deserialize<T>(byte[] Data);
Run Code Online (Sandbox Code Playgroud)
}
class Program
{
    static void Main(string[] args)
    {
        Serializer.Deserialize<Dummy>(new byte[20]);
    }
}
class Dummy : Data
{

}
Run Code Online (Sandbox Code Playgroud)

ja7*_*a72 8

更新 修复了代码/拼写错误

使用new()关键字

public interface IData
{
    public byte[] Serialize<T>(T obj);
    public T Deserialize<T>(byte[] Data);
}
public static class Serializer
{
    public static byte[] Serialize<T>(T Obj) where T : IData;
    public static T Deserialize<T>(byte[] data) where T : IData, new()
    {
        T res=new T();
        res.Deserialize<T>(data);
        return res;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Serializer.Deserialize<Dummy>(new byte[20]);
    }
}
class Dummy : IData
{

}
Run Code Online (Sandbox Code Playgroud)