2013-03-07 60 views
2

我想創建一個類型的實例,但直到運行時才知道該類型。如何在運行時填寫構造函數參數?

如何獲取構造函數的必需參數以將它們顯示給WPF窗口中的用戶?

有沒有像Visual Studio中使用的屬性窗口?

+0

看看HTTP ://stackoverflow.com/questions/6606515/name-of-the-constructor-arguments-in-c-sharp可能有幫助 – ceth 2013-03-07 08:07:55

回答

3

看一看可以從反射型獲得ParameterInfo對象:

Type type = typeof(T); 
ConstructorInfo[] constructors = type.GetConstructors(); 

// take one, for example the first: 
var ctor = constructors.FirstOrDefault(); 

if (ctor != null) 
{ 
    ParameterInfo[] params = ctor.GetParameters(); 

    foreach(var param in params) 
    { 
     Console.WriteLine(string.Format("Name {0}, Type {1}", 
      param.Name, 
      param.ParameterType.Name)); 
    } 
} 
1

這裏是搜索 - http://www.bing.com/search?q=c%23+reflection+constructor+parameters - 頂答案是ConstructorInfo與樣品:

public class MyClass1 
{ 
    public MyClass1(int i){} 
    public static void Main() 
    { 
     try 
     { 
      Type myType = typeof(MyClass1); 
      Type[] types = new Type[1]; 
      types[0] = typeof(int); 
      // Get the public instance constructor that takes an integer parameter. 
      ConstructorInfo constructorInfoObj = myType.GetConstructor(
       BindingFlags.Instance | BindingFlags.Public, null, 
       CallingConventions.HasThis, types, null); 
      if(constructorInfoObj != null) 
      { 
       Console.WriteLine("The constructor of MyClass1 that is a public " + 
        "instance method and takes an integer as a parameter is: "); 
       Console.WriteLine(constructorInfoObj.ToString()); 
      } 
      else 
      { 
       Console.WriteLine("The constructor of MyClass1 that is a public instance " + 
        "method and takes an integer as a parameter is not available."); 
      } 
     } 
     catch(Exception e) // stripped out the rest of excepitions... 
     { 
      Console.WriteLine("Exception: " + e.Message); 
     } 
    } 
}