日期:2014-05-17 浏览次数:21163 次
public static TypeDes CreateType(IDictionary<string, Type> propertys, Type parent) { StringBuilder sb = new StringBuilder(); var e = propertys.GetEnumerator(); while (e.MoveNext()) { sb.Append(e.Current.Key + ":" + e.Current.Value.FullName + ","); } string pname = MD5Core.GetHashString(sb.ToString(0, sb.Length - 1)); TypeDes typedes; if (!typeCache.TryGetValue(pname, out typedes)) { AssemblyName aName = new AssemblyName(Guid.NewGuid().ToString()); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run); ModuleBuilder mb = ab.DefineDynamicModule(aName.Name); TypeBuilder tb = mb.DefineType(pname, TypeAttributes.Public, parent);//parent就是所需继承的父类 ConstructorBuilder ctor0 = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); ILGenerator ctor0IL = ctor0.GetILGenerator(); ctor0IL.Emit(OpCodes.Ldarg_0); ctor0IL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)); ctor0IL.Emit(OpCodes.Ret); MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig; FieldBuilder fb = null; PropertyBuilder pb = null; MethodBuilder mba = null; ILGenerator il = null; foreach (string key in propertys.Keys) { //创建私有字段,存放属性值 fb = tb.DefineField("_" + key, propertys[key], FieldAttributes.Private); //创建公有属性 pb = tb.DefineProperty(key, PropertyAttributes.HasDefault, propertys[key], null); //设置GET方法 mba = tb.DefineMethod("get_" + key, getSetAttr, propertys[key], Type.EmptyTypes); il = mba.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, fb); il.Emit(OpCodes.Ret); pb.SetGetMethod(mba); //设置SET方法 mba = tb.DefineMethod("set_" + key, getSetAttr, null, new Type[] { propertys[key] }); il = mba.GetILGenerator();