c#创建动态匿名类型(var)

c#创建动态匿名类型(var),c#,winforms,types,C#,Winforms,Types,我需要创建一个匿名类型(必须是var)。像这样: var sizes = new { size = new { Medium = "1", Large = "-3", XL = "10%" } }; 它必须是动态的,以便下一次也可能发生这种情况: var sizes = new { size = new { 3XL = "5", 4XL = "5%", 5XL = "-10%" } }; 如何在C#winforms中实现这一点 如何填写变量大小?必须按这个顺序 您可以

我需要创建一个匿名类型(必须是var)。像这样:

var sizes = new { 
    size = new { Medium = "1", Large = "-3", XL = "10%" } 
};
它必须是动态的,以便下一次也可能发生这种情况:

var sizes = new { 
    size = new { 3XL = "5", 4XL = "5%", 5XL = "-10%" } 
};
如何在C#winforms中实现这一点


如何填写变量大小?必须按这个顺序

您可以在运行时创建包含任何类型的方法和属性的动态类型,使用
System.Reflection.Emit
,您可以在创建的动态类型中为属性分配默认值。这不是一个简单的练习,需要做一些工作,但是当基本代码完成后,在代码中使用它是很容易的

首先,您需要将动态类型附加到当前的
AppDomain

private AssemblyName _assemblyName;
private AssemblyBuilder _asssemblyBuilder;

private ModuleBuilder _moduleBuilder;
private Dictionary<SignatureBuilder, Type> _classes;

private ReaderWriterLock _rwLock;
private TypeBuilder _typeBuilder;
private string _typeName;

    /// <summary>
    /// Default constructor.
    /// </summary>
    /// <param name="moduleName">The name of the assembly module.</param>
    public DynamicTypeBuilder(string moduleName)
    {
        // Make sure the page reference exists.
        if (moduleName == null) throw new ArgumentNullException("moduleName");

        // Create the nw assembly
        _assemblyName = new AssemblyName(moduleName);
        _asssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName, AssemblyBuilderAccess.Run);

        // Create only one module, therefor the
        // modile name is the assembly name.
        _moduleBuilder = _asssemblyBuilder.DefineDynamicModule(_assemblyName.Name);

        // Get the class unique signature.
        _classes = new Dictionary<SignatureBuilder, Type>();
        _rwLock = new ReaderWriterLock();
    }
private AssemblyName\u AssemblyName;
私人组装商(asssemblyBuilder);;
专用模块生成器(ModuleBuilder);;
私人字典类;
私有读写器锁;
私人打字机(TypeBuilder);;
私有字符串_typeName;
/// 
///默认构造函数。
/// 
///程序集模块的名称。
公共DynamicTypeBuilder(字符串模块名)
{
//确保页面引用存在。
如果(moduleName==null)抛出新的ArgumentNullException(“moduleName”);
//创建nw部件
_assemblyName=新的assemblyName(moduleName);
_asssemblyBuilder=AppDomain.CurrentDomain.DefinedDynamicAssembly(\u assemblyName,AssemblyBuilderAccess.Run);
//仅创建一个模块,因此
//modile name是程序集名称。
_moduleBuilder=\u assemblyBuilder.definedDynamicModule(\u assemblyName.Name);
//获取类的唯一签名。
_classes=新字典();
_rwLock=新的ReaderWriterLock();
}
动态属性类可以是

/// <summary>
/// Dynamic property builder, with value assigned.
/// </summary>
public class DynamicPropertyValue
{
    object value;
    string name;
    Type type;

    /// <summary>
    /// Default constructor.
    /// </summary>
    /// <param name="name">The name of the property.</param>
    /// <param name="type">The type of the property</param>
    /// <param name="value">The value of the property.</param>
    public DynamicPropertyValue(string name, Type type, object value)
    {
        if (name == null) throw new ArgumentNullException("name");
        if (type == null) throw new ArgumentNullException("type");
        if (value == null) throw new ArgumentNullException("value");
        this.name = name;
        this.type = type;
        this.value = value;
    }

    /// <summary>
    /// Gets, the property name.
    /// </summary>
    public string Name
    {
        get { return name; }
    }

    /// <summary>
    /// Gets, the property type.
    /// </summary>
    public Type Type
    {
        get { return type; }
    }

    /// <summary>
    /// Gets, the property value.
    /// </summary>
    public object Value
    {
        get { return value; }
    }
}
/// <summary>
/// Dynamic method builder.
/// </summary>
public class DynamicMethod
{
    string name;
    IEnumerable<Type> parameters;
    Type returnType;
    Action<TypeBuilder> buildAction = null;

    /// <summary>
    /// Default constructor.
    /// </summary>
    /// <param name="name">The name of the method.</param>
    /// <param name="parameters">The collection parameter types.</param>
    /// <param name="returnType">The return type.</param>
    public DynamicMethod(string name, IEnumerable<Type> parameters, Type returnType)
    {
        if (name == null) throw new ArgumentNullException("name");

        this.name = name;
        this.parameters = parameters;
        this.returnType = returnType;
    }

    /// <summary>
    /// Default constructor.
    /// </summary>
    /// <param name="name">The name of the method.</param>
    /// <param name="parameters">The collection parameter types.</param>
    /// <param name="returnType">The return type.</param>
    /// <param name="buildAction">The build action.</param>
    public DynamicMethod(string name, IEnumerable<Type> parameters, Type returnType, Action<TypeBuilder> buildAction)
    {
        if (name == null) throw new ArgumentNullException("name");

        this.name = name;
        this.parameters = parameters;
        this.returnType = returnType;
        this.buildAction = buildAction;
    }

    /// <summary>
    /// Gets, the method name.
    /// </summary>
    public string Name
    {
        get { return name; }
    }

    /// <summary>
    /// Gets, the collection of parameters
    /// </summary>
    public IEnumerable<Type> Parameters
    {
        get { return parameters; }
    }

    /// <summary>
    /// Gets, the return type.
    /// </summary>
    public Type ReturnType
    {
        get { return returnType; }
    }

    /// <summary>
    /// Gets, build action.
    /// </summary>
    public Action<TypeBuilder> BuildAction
    {
        get { return buildAction; }
    }
}
//
///动态特性生成器,具有指定的值。
/// 
公共类DynamicPropertyValue
{
目标价值;
字符串名;
类型;
/// 
///默认构造函数。
/// 
///属性的名称。
///属性的类型
///财产的价值。
公共DynamicPropertyValue(字符串名称、类型、对象值)
{
如果(name==null)抛出新的ArgumentNullException(“name”);
如果(type==null)抛出新的ArgumentNullException(“type”);
如果(value==null)抛出新的ArgumentNullException(“value”);
this.name=名称;
this.type=type;
这个值=值;
}
/// 
///获取属性名。
/// 
公共字符串名
{
获取{返回名称;}
}
/// 
///获取属性类型。
/// 
公共类型
{
获取{返回类型;}
}
/// 
///获取属性值。
/// 
公共对象价值
{
获取{返回值;}
}
}
动态方法类可以是

/// <summary>
/// Dynamic property builder, with value assigned.
/// </summary>
public class DynamicPropertyValue
{
    object value;
    string name;
    Type type;

    /// <summary>
    /// Default constructor.
    /// </summary>
    /// <param name="name">The name of the property.</param>
    /// <param name="type">The type of the property</param>
    /// <param name="value">The value of the property.</param>
    public DynamicPropertyValue(string name, Type type, object value)
    {
        if (name == null) throw new ArgumentNullException("name");
        if (type == null) throw new ArgumentNullException("type");
        if (value == null) throw new ArgumentNullException("value");
        this.name = name;
        this.type = type;
        this.value = value;
    }

    /// <summary>
    /// Gets, the property name.
    /// </summary>
    public string Name
    {
        get { return name; }
    }

    /// <summary>
    /// Gets, the property type.
    /// </summary>
    public Type Type
    {
        get { return type; }
    }

    /// <summary>
    /// Gets, the property value.
    /// </summary>
    public object Value
    {
        get { return value; }
    }
}
/// <summary>
/// Dynamic method builder.
/// </summary>
public class DynamicMethod
{
    string name;
    IEnumerable<Type> parameters;
    Type returnType;
    Action<TypeBuilder> buildAction = null;

    /// <summary>
    /// Default constructor.
    /// </summary>
    /// <param name="name">The name of the method.</param>
    /// <param name="parameters">The collection parameter types.</param>
    /// <param name="returnType">The return type.</param>
    public DynamicMethod(string name, IEnumerable<Type> parameters, Type returnType)
    {
        if (name == null) throw new ArgumentNullException("name");

        this.name = name;
        this.parameters = parameters;
        this.returnType = returnType;
    }

    /// <summary>
    /// Default constructor.
    /// </summary>
    /// <param name="name">The name of the method.</param>
    /// <param name="parameters">The collection parameter types.</param>
    /// <param name="returnType">The return type.</param>
    /// <param name="buildAction">The build action.</param>
    public DynamicMethod(string name, IEnumerable<Type> parameters, Type returnType, Action<TypeBuilder> buildAction)
    {
        if (name == null) throw new ArgumentNullException("name");

        this.name = name;
        this.parameters = parameters;
        this.returnType = returnType;
        this.buildAction = buildAction;
    }

    /// <summary>
    /// Gets, the method name.
    /// </summary>
    public string Name
    {
        get { return name; }
    }

    /// <summary>
    /// Gets, the collection of parameters
    /// </summary>
    public IEnumerable<Type> Parameters
    {
        get { return parameters; }
    }

    /// <summary>
    /// Gets, the return type.
    /// </summary>
    public Type ReturnType
    {
        get { return returnType; }
    }

    /// <summary>
    /// Gets, build action.
    /// </summary>
    public Action<TypeBuilder> BuildAction
    {
        get { return buildAction; }
    }
}
//
///动态方法生成器。
/// 
公共类动态方法
{
字符串名;
可数参数;
类型返回类型;
Action buildAction=null;
/// 
///默认构造函数。
/// 
///方法的名称。
///集合参数类型。
///返回类型。
公共动态方法(字符串名称、IEnumerable参数、类型returnType)
{
如果(name==null)抛出新的ArgumentNullException(“name”);
this.name=名称;
此参数=参数;
this.returnType=returnType;
}
/// 
///默认构造函数。
/// 
///方法的名称。
///集合参数类型。
///返回类型。
///构建操作。
公共动态方法(字符串名称、IEnumerable参数、类型returnType、操作buildAction)
{
如果(name==null)抛出新的ArgumentNullException(“name”);
this.name=名称;
此参数=参数;
this.returnType=returnType;
this.buildAction=buildAction;
}
/// 
///获取方法名。
/// 
公共字符串名
{
获取{返回名称;}
}
/// 
///获取参数的集合
/// 
公共IEnumerable参数
{
获取{返回参数;}
}
/// 
///获取返回类型。
/// 
公共类型返回类型
{
获取{return returnType;}
}
/// 
///获取,生成操作。
/// 
公共行动
{
获取{return buildAction;}
}
}
开始创建过程

    /// <summary>
    /// Create a new instance of the dynamic type.
    /// </summary>
    /// <param name="typeName">The name of the type.</param>
    /// <param name="properties">The collection of properties to create in the type.</param>
    /// <param name="methods">The collection of methods to create in the type.</param>
    /// <returns>The new instance of the type.</returns>
    public object Create(string typeName, IEnumerable<DynamicPropertyValue> properties, IEnumerable<DynamicMethod> methods)
    {
        // Make sure the page reference exists.
        if (typeName == null) throw new ArgumentNullException("typeName");
        if (properties == null) throw new ArgumentNullException("properties");
        if (methods == null) throw new ArgumentNullException("methods");

        _typeName = typeName;

        // Create the dynamic type collection
        List<DynamicProperty> prop = new List<DynamicProperty>();
        foreach (DynamicPropertyValue item in properties)
            prop.Add(new DynamicProperty(item.Name, item.Type));

        // Return the create type.
        object instance = CreateEx(typeName, prop.ToArray(), methods);
        PropertyInfo[] infos = instance.GetType().GetProperties();

        // Assign each type value
        foreach (PropertyInfo info in infos)
            info.SetValue(instance, properties.First(u => u.Name == info.Name).Value, null);

        // Return the instance with values assigned.
        return instance;
    }
//
///创建动态类型的新实例。
/// 
///类型的名称。
///要在类型中创建的属性集合。
///要在类型中创建的方法的集合。
///类型的新实例。
创建公共对象(字符串类型名、IEnumerable属性、IEnumerable方法)
{
//确保页面引用存在。
如果(typeName==null)抛出新的ArgumentNullException(“typeName”);
如果(properties==null)抛出新的ArgumentNullException(“properties”);
如果(methods==null)抛出新的ArgumentNullException(“方法”);
_typeName=typeName;
//创建动态类型集合
列表属性=新列表();
foreach(属性中的DynamicPropertyValue项)
prop.Add(新的DynamicProperty(item.Name,item.Type));
//返回创建类型。
对象实例=CreateEx(类型名,prop.ToArray(),方法);
PropertyInfo[]infos=instance.GetType().GetProperties();
//分配每个类型的值
foreach(信息中的PropertyInfo信息)
info.SetValue(实例,properties.First(u=>u.Name==info.Name).Value,null);
//返回指定了值的实例。
返回实例;
}

如果您可以使用动态类型生成器的完整源代码,请访问

,您为什么要这样做?请查看
ExpandoObject
另一种可能是
enum