[英]Can I implement a generic type and pass it a type that is known only at runtime?
I'm pulling serialized data from a database along with an object type (where one field contains the object type and one contains an XML string of serialized data). 我正在从数据库中提取序列化数据以及对象类型(其中一个字段包含对象类型,一个字段包含序列化数据的XML字符串)。
I've got a generic serializer that has a serialize and deserialize method: 我有一个具有序列化和反序列化方法的通用序列化器:
public static class Serializer<T>
{
public static string Serialize(T objectData) { }
public static T Deserialize(string xmlData) { }
}
Given that the object type is specified in the database field, is there any way for me to dynamically set what T is? 假定在数据库字段中指定了对象类型,那么我有什么方法可以动态设置T是什么? - This is my line of thought (although this doesn't work):
-这是我的想法(尽管这行不通):
Type t = Type.GetType(objectTypeName);
t objData = Serializer<t>.Deserialize(objectXmlString);
I was hoping to refactor some code out of a switch statement where T is a set value, but I can't figure out if it can be done, or if so, how I would go about that. 我希望从switch语句中重构一些代码,其中T是一个设置值,但我不知道是否可以完成,或者如果可以,我将如何处理。
Thanks in advance. 提前致谢。
You can do this, but it involves reflection - MakeGenericType
, in particular: 您可以执行此操作,但是涉及反射
MakeGenericType
,尤其是:
typeof(Serializer<>).MakeGenericType(t).GetMethod("Deserialize").Invoke(...);
I haven't completed that, since your example is confusing; 由于您的示例令人困惑,因此我还没有完成。 the method is instance, but is called as though it were static.
该方法是实例,但是被称为静态方法。
Interestingly (perhaps), dynamic
might make this easier in 4.0 - I don't have my VM to hand, but imagine: 有趣的是(也许),
dynamic
可能会使它在4.0中变得更容易-我没有虚拟机,但可以想象:
static void SomeGenericMethod<T>(T arg) { Serializer<T>.SomeMethod(arg); }
...
dynamic obj = ...
SomeGenericMethod(obj);
I'd need to check, but I expect that would do a lot of the heavy lifting for us. 我需要检查一下,但是我希望这对我们来说可以做很多繁重的工作。
The other common approach is to expose methods that work on a Type
, rather than via generics. 另一种常见的方法是公开在
Type
上工作的方法,而不是通过泛型。
No. However, it should not be too difficult to create additional overloads of your serialisation methods to handle this requirement: 不会。但是,创建序列化方法的其他重载来处理此要求应该不太困难:
public string Serialize(Type objectType, object objectData) { }
public object Deserialize(Type objectType, string xmlData) { }
The serialisation APIs in .NET all take Type
instances as parameters anyway. 无论如何,.NET中的序列化API都将
Type
实例作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.