我基本上有这样的东西:
void Foo(Type ty)
{
var result = serializer.Deserialize<ty>(inputContent);
}
Foo(typeof(Person));
Deserialize<ty>
不起作用,因为它需要 Deserialize<Person>
反而。我该如何解决这个问题?
我还想了解泛型是如何工作的以及为什么它不接受 ty
这是 typeof(Person)
.
编辑:我应该提到这是一个人为的例子。我实际上无法更改函数的签名,因为它实现了一个接口(interface)。
编辑:序列化程序是一个 JavascriptSerializer 并在此处作为操作过滤器实现。它的名字是这样的:
[JsonFilter(Param="test", JsonDataType=typeof(Person))]
解决方案
根据 Marc 和 Anton 的回答:
var result = typeof(JavaScriptSerializer).GetMethod("Deserialize")
.MakeGenericMethod(JsonDataType)
.Invoke(serializer, new object[] { inputContent });
最佳答案
那是哪个序列化器?如果您只知道运行时(不是编译时)的类型
,并且它没有非通用 API,那么您可能必须使用 MakeGenericMethod
:
void Foo(Type ty)
{
object result = typeof(ContainingClass).GetMethod("Bar").
.MakeGenericMethod(ty).Invoke(null, new object[] {inputContent});
}
public static T Bar<T>(SomeType inputContent) {
return serializer.Deserialize<T>(inputContent);
}
关于c# - 如何将 Type 实例转换为泛型类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/856665/