2012-08-14 9 views
16

問題があります。クラスのインスタンスを名前で作成したい。 私が見つけたActivator.CreateInstancehttp://msdn.microsoft.com/en-us/library/d133hta4.aspxそれはうまく動作し、私はこれを見つけた: Setting a property by reflection with a string value あまりにも。C#クラスのインスタンスを作成し、文字列に名前でプロパティを設定します。

しかし、これをどのように行うには?私はクラスの名前を知っている、私はそのクラスのすべてのプロパティを知っていると私は文字列でこれを持っています。たとえば :インスタンスを作成し、プロパティにいくつかの値を設定する方法

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

+1

このようなことはほとんどできません。オブジェクトの作成とプロパティの設定は、Reflectionの観点からは完全に独立しています。さらに、各プロパティを個別に設定する必要があります。もちろん、パックされた文字列を部分的に分割し、分析してからオブジェクトを作成してプロフェッショナルを設定するヘルパー関数を作成することもできます。私はそれがあなたのためのトリックを行うべきだと思います。 – quetzalcoatl

答えて

44

あなたは、リフレクションを使用することができます。

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); 
    } 
} 
+1

@ダーリン、私は同じコードをテストし、 "アセンブリ 'GenerateClassDynamically_ConsoleApp1、バージョン= 1.0.0.0、カルチャ=ニュートラル、PublicKeyToken = null'から 'Foo'型を読み込めませんでした。 。例外タイプは "System.TypeLoad Exception"です。なぜそれが現れているのか分かりません。 –

+0

@ダリン、私は同じコードをテストし、 "アセンブリ 'GenerateClassDynamically_ConsoleApp1、バージョン= 1.0.0.0、カルチャ=ニュートラル、PublicKeyToken = null'から 'Foo'型を読み込めませんでした。 。例外タイプは "System.TypeLoad Exception"です。なぜそれが現れているのか分かりません。私を助けてください。私はSAPサービスを取得する同じ要件があり、私はクラスを生成し、そのクラスにプロパティを動的に追加し、応答データを取得するためにサービスに返す必要があります。 –

1

あなたはSystem.TypeLoad例外を持っていた場合、自分のクラス名が間違っています。

メソッドType.GetTypeには、アセンブリ修飾名を入力する必要があります。 GenerateClassDynamically_ConsoleApp1.Foo

それは別のアセンブリ内にある場合JOUはカンマ(https://stackoverflow.com/a/3512351/1540350の詳細)の後にアセンブリ名を入力する必要があります:たとえば、プロジェクト名である Type.GetType( "GenerateClassDynamically_ConsoleApp1.Foo、GenerateClassDynamically_ConsoleApp1 ");

-3
Type tp = Type.GetType(Namespace.class + "," + n.Attributes["ProductName"].Value + ",Version=" + n.Attributes["ProductVersion"].Value + ", Culture=neutral, PublicKeyToken=null"); 
if (tp != null) 
{ 
    object o = Activator.CreateInstance(tp); 
    Control x = (Control)o; 
    panel1.Controls.Add(x); 
} 
関連する問題