2012-11-23 31 views
3

調用構造函數像下面一個非常簡單的類,的反思與ConstructorInfo

class Program 
{ 

    public Program(int a, int b, int c) 
    { 
     Console.WriteLine(a); 
     Console.WriteLine(b); 
     Console.WriteLine(c); 
    } 
} 

,我使用反射來調用構造函數

這樣的事情...

var constructorInfo = typeof(Program).GetConstructor(new[] { typeof(int), typeof(int),  typeof(int) }); 
     object[] lobject = new object[] { }; 
     int one = 1; 
     int two = 2; 
     int three = 3; 
     lobject[0] = one; 
     lobject[1] = two; 
     lobject[2] = three; 

     if (constructorInfo != null) 
     { 
      constructorInfo.Invoke(constructorInfo, lobject.ToArray); 
     } 

但是我收到一個錯誤,提示「對象與目標類型構造函數信息不匹配」。

任何幫助/意見非常感謝。 在此先感謝。

回答

9

只要您調用構造函數,而不是一個對象的實例方法,則不需要將constructorInfo作爲參數傳遞。

var constructorInfo = typeof(Program).GetConstructor(
          new[] { typeof(int), typeof(int), typeof(int) }); 
if (constructorInfo != null) 
{ 
    object[] lobject = new object[] { 1, 2, 3 }; 
    constructorInfo.Invoke(lobject); 
} 

對於KeyValuePair<T,U>

public Program(KeyValuePair<int, string> p) 
{ 
    Console.WriteLine(string.Format("{0}:\t{1}", p.Key, p.Value)); 
} 

static void Main(string[] args) 
{ 
    var constructorInfo = typeof(Program).GetConstructor(
          new[] { typeof(KeyValuePair<int, string>) }); 
    if (constructorInfo != null) 
    { 
     constructorInfo.Invoke(
      new object[] { 
       new KeyValuePair<int, string>(1, "value for key 1") }); 
    } 

    Console.ReadLine(); 
} 
+0

唷!我怎麼錯過這個?謝謝.... –

+0

假設如果我在構造函數中有一個keyvalue對,那麼我可以用同樣的方法調用嗎? –

+0

@nowhewhomustnotbenamed。,看我的編輯.... – horgh