2013-03-07 59 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); 
     } 
    } 
}