C#如何在程序执行过程中创建一个对象,指定类型并赋值?

How can I create an object in C# during program execution, specify the type and assign a value?

帮帮我,在C#中有没有可能做一个动态创建的class,其properties and their types的数量是事先不知道的?

比如有一个POCOclass,加载的时候需要加载一个文件模板(例如-XML),其中对象(属性)的名称,它们的将指定类型和值。

在我看来,这可以通过 dictionarywrapper class 来完成(也许我错了,这是一个错误的决定)。但是我无法弄清楚如何在不创建数十个 as 条件?

public static class Program
{
    public static void Main()
    {
        Dictionary<string, ElemType> keys = new Dictionary<string, ElemType>();
        keys.Add(
            "UserID", new ElemType() { NameType = "System.Int32", ValueType = "123" }
            );
        keys.Add(
            "UserName", new ElemType() { NameType = "System.String", ValueType = "abc" }
            );

        var type = Type.GetType(keys["UserID"].NameType);
        ///var elem = (???type)Activator.CreateInstance(type);
    }
}

public class ElemType
{
    public string NameType { get; set; }
    public object ValueType { get; set; }
}

您可以使用可以在运行时定义属性的 ExpandObject。下面是一个非常简单的工作原型

    static void Main(string[] args)
    {
        // Define a type with the following properties
        //  string  Name
        //  int     Age
        //  bool    Alive


        dynamic test2 = CreateInstance(
            ("Name", "John"),
            ("Age", 50),
            ("Alive", true));

        Console.WriteLine($"Name:{test2.Name} Age:{test2.Age}");
    }

    static dynamic CreateInstance(params (string name, object value)[] properties)
    {
        dynamic eo = new ExpandoObject();
        var dict = (IDictionary<string, object>)eo;

        foreach (var item in properties)
        {
            dict[item.name] = item.value;
        }

        return eo;
    }