2

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

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

是否可以使用 Visual Studio 中的属性窗口之类的东西?

4

2 回答 2

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));
    }
}
于 2013-03-07T08:08:46.510 回答
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);
        }
    }
}
于 2013-03-07T08:10:21.090 回答