从类型创建泛型类的实例

And*_*ard 1 c# generics

我有一个返回一个对象的方法这个类:

public class Deserializer<T>
{
    public static T FromJson(string json)
    {
        return new JavaScriptSerializer().Deserialize<T>(json);
    }   
}
Run Code Online (Sandbox Code Playgroud)

我有一个类型.如何基于此类型创建Deserializer类的实例?以下显然不起作用:

var type = typeOf(MyObject);
var foo = Deserializer<type>.FromJson(json);
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 8

您可以为在编译时不知道类型的消费者提供非泛型版本(这是您在公开API时的一种很好的做法):

public class Deserializer
{
    public static T FromJson<T>(string json)
    {
        return new JavaScriptSerializer().Deserialize<T>(json);
    }

    public static object FromJson(string json, Type type)
    {
        return new JavaScriptSerializer().Deserialize(json, type);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在编译时知道类型的消费者:

Foo foo = Deserializer.FromJson<Foo>(json);
Run Code Online (Sandbox Code Playgroud)

和在编译时不知道类型的消费者:

Type type = ...
object instance = Deserializer.FromJson(json, type);
Run Code Online (Sandbox Code Playgroud)