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 Dictio开发者_运维技巧nary 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);
}
I don't believe you can do this at runtime (generate a class), what you could do is make use of the ExpandoObject available in .net 4.0.
精彩评论