2017-06-06 10 views
0

クラスを動的に作成し、そのクラスにプロパティを動的に追加したい場合は とし、そのクラスのオブジェクトとそのクラスの汎用リストを作成し、 : enter image description here動的クラスの作成とアクセスクラスのプロパティC#

+0

何をしようとしたのですか?実行時にクラスを作成する場合、デザイナーでプロパティを表示することはできません。インターフェイスを実装していない限り –

+0

あなたは匿名のタイプを検討しましたか? https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types – Droxx

+0

C#でmixin機能を利用しようとしていますか?残念ながら、C3はミックスインをサポートしていません。 https://en.wikipedia.org/wiki/Mixin –

答えて

-1

あなたはとあなたのクラスの一覧を作成することができます。

List<ClassA> list = new List<ClassA>(); 

としてリストにそのクラスのあなたの作成したオブジェクトを追加します。

list.Add(dynamic); 
+0

_ClassA_に動的オブジェクトを追加したくありません_ClassA_を動的に作成し、そのクラスのリストを作成し、そのクラスのオブジェクトをリストに追加し、上の図に示すようにそのクラスのプロパティにアクセスしたいとします。 – Abhay

-1

あなたは、単に未定義の形式のデータが必要な場合は、辞書
例使用することができます
辞書<文字列、オブジェクト>のparam =新しい辞書<文字列、オブジェクト>を();
param.Add( "msg"、 "hello");
param.Add( "number"、1234); Microsoftは、動的LINQクエリを作成するためのライブラリをリリース

1

int型として文字列
のparamとして
のparam [ "MSG"] [ "数"]:として

後でアクセスすることができます。実行時にクラスを作成するために使用できるClassFactoryがあります。

ここでは例です:

class Program 
{ 
    static void SetPropertyValue(object instance, string name, object value) 
    { 
     // this is just for example, it would be wise to cache the PropertyInfo's 
     instance.GetType().GetProperty(name)?.SetValue(instance, value); 
    } 

    static void Main(string[] args) 
    { 
     // create an enumerable which defines the properties 
     var properties = new[] 
     { 
      new DynamicProperty("Name", typeof(string)), 
      new DynamicProperty("Age", typeof(int)), 
     }; 

     // create the class type 
     var myClassType = ClassFactory.Instance.GetDynamicClass(properties); 

     // define a List<YourClass> type. 
     var myListType = typeof(List<>).MakeGenericType(myClassType); 

     // create an instance of the list 
     var myList = (IList)Activator.CreateInstance(myListType); 

     // create an instance of an item 
     var first = Activator.CreateInstance(myClassType); 

     // use the method above to fill the properties 
     SetPropertyValue(first, "Name", "John"); 
     SetPropertyValue(first, "Age", 24); 

     // add it to the list 
     myList.Add(first); 


     var second = Activator.CreateInstance(myClassType); 

     SetPropertyValue(second, "Name", "Peter"); 
     SetPropertyValue(second, "Age", 38); 

     myList.Add(second); 
    } 
} 

あなたがここでそれをダウンロードすることができます:あなたはDynamicLibrary.cs

関連する問題