如何在运行时填写构造函数参数?

时间:2013-03-07 08:02:00

标签: c# wpf reflection

我想创建一个类型的实例,但直到运行时我才知道类型。

如何获取构造函数所需的参数以在WPF窗口中向用户显示它们?

是否有类似于Visual Studio中的属性窗口的东西?

2 个答案:

答案 0 :(得分: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 :(得分: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);
        }
    }
}