internal interface Rule {
}
private class Rule<T> : Rule {
//Properties & Other Stuff
}
void method() {
//For simplicity I used string here. It can be anything when the code is in context
Type _type = typeof(string);
Rule[] _rules;
//This is causing an error because _type could not be found
_rules = new Rule<_type>[] { };
}
是否可以实例化一个存储在变量中的泛型类?
- 编辑
从我的第一个例子开始,我认为我可以应用相同的概念来调用方法。但似乎我错了。我试图使用newtonsoft json库将字符串反序列化为泛型类型。我发现这个question允许你调用泛型类型的方法。我环顾四周如何将对象转换为_foo,但只能找到类型已知的转换。有什么想法吗?
Using Newtonsoft.Json;
void method() {
//For simplicity I used string here. It can be anything when the code is in context
Type _type = typeof(string);
Rule[] _rules;
// ------------------ New Additions ----------------
var _foo = (Rule[])Array.CreateInstance(typeof(Rule<>).MakeGenericType(_type),0);
MethodInfo method = typeof(JsonConvert).GetMethod("DeserializeObject");
MethodInfo generic = method.MakeGenericMethod(_foo.GetType());
//How do you cast this to a type _myType?
_rules = generic.Invoke(this, new[] { "JSON Data" });
}
答案 0 :(得分:2)
这是可能的,但你必须使用反射:
Type genericTypeDefinition = typeof(Rule<>);
Type genericType = genericTypeDefinition.MakeGenericType(_type);
Rule[] array = (Rule[])Array.CreateInstance(genericType, 0);