28

問題があります。名前でクラスのインスタンスを作成したい。Activator.CreateInstance http://msdn.microsoft.com/en-us/library/d133hta4.aspxを見つけましたが、正常に動作し、これを見つけました: 文字列値を使用したリフレクションによるプロパティの設定 も。

しかし、これを両方行うにはどうすればよいでしょうか。つまり、クラスの名前を知っていて、そのクラスのすべてのプロパティを知っていて、これを文字列で持っています。例えば:

string name = "MyClass";
string property = "PropertyInMyClass";

インスタンスを作成し、プロパティに値を設定する方法は?

4

3 に答える 3

69

リフレクションを使用できます:

using System;
using System.Reflection;

public class Foo
{
    public string Bar { get; set; }
}

public class Program
{
    static void Main()
    {
        string name = "Foo";
        string property = "Bar";
        string value = "Baz";

        // Get the type contained in the name string
        Type type = Type.GetType(name, true);

        // create an instance of that type
        object instance = Activator.CreateInstance(type);

        // Get a property on the type that is stored in the 
        // property string
        PropertyInfo prop = type.GetProperty(property);

        // Set the value of the given property on the given instance
        prop.SetValue(instance, value, null);

        // at this stage instance.Bar will equal to the value
        Console.WriteLine(((Foo)instance).Bar);
    }
}
于 2012-08-14T18:52:18.140 に答える