2016-09-12 1 views
0

System.Type으로 실험 중입니다. 다음 코드, I는 어레이 형으로 사용 GetConstructors :GetConstructors가 선언 된 생성자를 찾지 못했습니다.

using System; 
using System.Reflection; 

class Animal 
{ 
    public Animal (string s) 
    { 
     Console.WriteLine(s); 
    } 
} 

class Test 
{ 
    public static void Main() 
    { 
     Type AnimalArrayType = typeof(Animal).MakeArrayType(); 
     Console.WriteLine(AnimalArrayType.GetConstructors()[0]); 
    } 
} 

출력은 : Void .ctor(Int32). 왜? Void .ctor(System.string)이 아니어야합니까?

답변

3

.MakeArrayType()을 호출 했으므로 Animal의 배열에서 반사를 수행 중이므로 Animal이 아닙니다. 그것을 제거하면 예상 한 생성자를 얻게됩니다.

Type AnimalArrayType = typeof(Animal); 
Console.WriteLine(AnimalArrayType.GetConstructors()[0]); 

배열 유형의 요소 유형을 얻으려면 다음과 같이하면됩니다.

Type AnimalArrayType = typeof(Animal[]); 
Console.WriteLine(AnimalArrayType.GetElementType().GetConstructors()[0]); 

원하는 크기의 배열을 만들기 위해서는 이것을 사용할 수 있습니다.

Type AnimalArrayType = typeof(Animal[]); 
var ctor = AnimalArrayType.GetConstructor(new[] { typeof(int) }); 
object[] parameters = { 3 }; 
var animals = (Animal[])ctor.Invoke(parameters); 
+0

여기서'Void .ctor (Int32) '는 어디에서 왔습니까? – HeyJude

+0

배열 유형의 생성자가 표시됩니다. 정수를 취하는 것이 있습니다. – recursive

+0

감사합니다. 그리고 관련된 하나 : 반환 된 생성자를 사용하여 예를 들어 3 개 요소의 'Animal []'을 인스턴스화하려면 어떻게해야합니까? 나는 다음과 같은 시도를 시도했다 : AnimalArrayType = typeof (Animal []); 타입 [] passed_params = new Type [1] {typeof (string)}; ConstructorInfo ci = AnimalArrayType.GetElementType(). GetConstructors() [0]; Animal [] animal_arr = (동물 []) ci.Invoke (새 개체 [] { "monkey"}); ' – HeyJude

관련 문제