【问题标题】:Dynamic Class creation and access class properties c#动态类创建和访问类属性 c#
【发布时间】:2017-11-07 12:35:25
【问题描述】:

我想动态地创建一个类并动态地为该类添加属性 然后我想创建该类的一个对象和该类的通用列表并访问它,如下所示:

【问题讨论】:

标签: c# class object dynamic dynamic-class


【解决方案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

【讨论】:

    【解决方案2】:

    您可以使用以下方法创建班级列表:

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

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

    list.Add(dynamic);
    

    【讨论】:

    • 我不想将动态对象添加到 ClassA 我想动态创建 ClassA 并列出该类并添加对象该类要列出并访问该类的属性,如上图所示。
    【解决方案3】:

    如果您只是想要未定义格式的数据,您可以使用 Dictionary
    例如:
    字典 param = new Dictionary();
    参数.Add("msg", "hello");
    param.Add("号码", 1234);

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 2013-07-12
      • 2010-12-28
      • 1970-01-01
      • 2019-05-02
      • 2011-05-05
      相关资源
      最近更新 更多