2014-11-22 3 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>[] { }; 
} 

변수에 저장된 일반 형식의 클래스를 인스턴스화 할 수 있습니까? generic 형식을 변수로 사용하여 제네릭 클래스를 초기화하십시오.

- EDIT 내 첫 번째 예에서

은 내가 메소드를 호출에 대해 같은 개념을 적용 할 수있을 것이라고 생각했다. 그러나 내가 틀렸던 것 같습니다. newtonsoft json 라이브러리를 사용하여 문자열을 일반 형식으로 deserialize하려고합니다. 제네릭 형식의 메서드를 호출 할 수있는이 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의 비틀기 때문이 아닙니다. -type-at-runtime –

+0

가능한 복제본 [일반 클래스의 유형 매개 변수로 인스턴스화 된 System.Type 전달] (http://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as) -a-type-parameter-for-generic-class) –

답변

2

이 가능하지만, 당신은 반사를 사용해야합니다 :

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