【发布时间】:2014-11-22 11:49:12
【问题描述】:
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" });
}
【问题讨论】:
-
这主要是 stackoverflow.com/questions/1151464/… 的重复...但不完全是由于 stackoverflow.com/questions/400900/… 的扭曲
标签: c# generics initialization