2014-11-22 132 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);