簡體   English   中英

動態類創建和訪問類屬性C#

[英]Dynamic Class creation and access class properties c#

我想動態創建一個類,並動態地向該類添加屬性,然后再創建該類的對象和該類的通用列表,並按如下方式訪問它: 在此處輸入圖片說明

Microsoft發布了一個用於創建動態linq查詢的庫。 有一個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

您可以使用以下方法創建課程列表:

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

並使用以下命令將創建的該類的對象添加到“列表”中:

list.Add(dynamic);

如果您只想使用未定義格式的數據,則可以使用Dictionary
例如:

以后可以通過以下方式訪問:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM