0

我想动态创建一个类并向该类动态添加属性,之后我想创建该类的一个对象和该类的通用列表并访问它,如下所示: 在此处输入图像描述

4

3 回答 3

1

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

于 2017-06-07T06:36:59.403 回答
-1

如果您只是想要未定义格式的数据,您可以使用 Dictionary
Ex:
Dictionary < string, object > param = new Dictionary< string, object>();
参数。添加(“味精”,“你好”);
参数.Add("数字", 1234);

稍后可以通过以下方式访问:
param["msg"] as string
param["number"] as int

于 2017-06-06T13:41:57.333 回答
-1

您可以使用以下命令创建班级列表:

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

并将您创建的该类的对象添加到列表中:

list.Add(dynamic);
于 2017-06-06T13:15:08.837 回答