【问题标题】:Initialize a generic class with the generic type as a variable用泛型类型作为变量初始化泛型类
【发布时间】: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" });
}

【问题讨论】:

标签: c# generics initialization


【解决方案1】:

这是可能的,但你必须使用反射:

Type genericTypeDefinition = typeof(Rule<>);
Type genericType = genericTypeDefinition.MakeGenericType(_type);
Rule[] array = (Rule[])Array.CreateInstance(genericType, 0);

【讨论】:

    猜你喜欢
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 2016-04-11
    • 1970-01-01
    相关资源
    最近更新 更多