2014-11-22 119 views
0
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

这主要是复制http://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-的c-sharp-object-using-reflection ...但不完全是由于扭曲http://stackoverflow.com/questions/400900/how-can-i-create-an-instance-of-an-arbitrary-array运行时类型 – 2014-11-22 03:03:32

+0

[将实例化的System.Type传递为泛型类的类型参数](http://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as -a型参数换一个泛型类) – 2014-11-22 03:06:31

回答

2

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

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