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 に答える