我有一个使用如下通用参数创建的 Json 反序列化器类:
Deserializer<T> results = Deserializer<T>.FromFile(file);
其中 T 是任意数量的类型实现的接口(interface)。
我希望以字符串形式的类名来选择 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});
谢谢大家的帮助
请您参考如下方法:
将 ModiX 链接中的答案应用于您的代码,应该会产生如下结果:
Type genericType = typeof(Deserializer<>);
Type[] typeArgs = { Type.GetType("Person") };
Type deserializerType = genericType.MakeGenericType(typeArgs);
object deserializer = Activator.CreateInstance(deserializerType);
MethodInfo fromFileMethod = deserializerType.GetMethod("FromFile");
fromFileMethod.Invoke(deserializer, new[] { file });
线
MethodInfo closedMethod = genericMethod.MakeGenericMethod(typeof(Something));
如果您的方法是通用的,则使用它,在您的情况下,如果它看起来像这样:
Deserializer<T>.FromFile<T2>(...)
