【发布时间】:2016-05-06 06:19:06
【问题描述】:
我有一个使用这样的通用参数创建的 Json 反序列化器类:
Deserializer<T> results = Deserializer<T>.FromFile(file);
其中 T 是任意数量的类型实现的接口。
我希望以字符串形式的类名选择 T,例如“Person” Person 类实现了 T。
所以可以这样写:
Deserializer<Type.GetType("Person")> results = Deserializer<Type.GetType("Person")>.FromFile(file);
我已经在上面尝试过,但它给了我一个错误:
Using the generic type 'Deserializer<T>' requires 1 type arguments
我也看过这个
但尝试使用其中一些会导致其他错误,例如:
randomVariable is a 'field' but is used like a 'type'
我的代码有错误还是我的处理方式不对?
我怎样才能让它工作?
解决方案 我的最终代码是
Type genericType = typeof(Deserializer<>);
Type[] typeArgs = {Type.GetType("Person")};
Type deserialiserType = genericType.MakeGenericType(typeArgs);
object repository = Activator.CreateInstance(deserialiserType);
MethodInfo genericMethod = deserialiserType.GetMethod("FromFile");
genericMethod.Invoke(repository, new[] {file});
谢谢大家的帮助
【问题讨论】:
-
你能否详细说明你的目标,你所说的并不完全是计算出来的。您是在尝试基于 JSON 构建
interface或class,还是尝试将值分配给存在的类? -
告诉我们您使用的是什么序列化程序,以便我们给您一些建议。
-
如果提供的类名实现了多个接口怎么办?
-
我认为这对您可能非常有用:stackoverflow.com/questions/11107536/…。出自乔恩·斯基特的口中!
-
@barrick 我可以保证它只实现一次类。