简体   繁体   中英

I have Dynamic Property Names and Their Types stored in a Dictionary, how do i build a class dynamically out of it in silverlight?

I have a dynamic Dictionary that gets filled at run time,

Dictionary<string, Type> (where string will have the property name and Type will have the type of the property ) now i want to generate a class out of it,

how do i achieve it in silverlight?

        Dictionary<string, Type> props = new Dictionary<string,Type>();
        props["Id"] = typeof(int);
        props["Name"] = typeof(string);

        AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("AsemName"), AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder mb = ab.DefineDynamicModule("ModuleName");
        TypeBuilder typeBuilder = mb.DefineType("TypeName", TypeAttributes.Public);
        foreach(var name in props.Keys){
            typeBuilder.DefineField(name, props[name], FieldAttributes.Public);
        }
        Type type = typeBuilder.CreateType();

        object o = type.GetConstructor(Type.EmptyTypes).Invoke(null);

        //Verfication:
        Console.WriteLine("Type is: " + o.GetType());

        foreach (var field in o.GetType().GetFields())
        {
            Console.WriteLine(" " + field.Name + " of type " + field.ReflectedType);
        }

我不相信您可以在运行时执行此操作(生成类),您可以做的是利用.net 4.0中可用的ExpandoObject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM