我生如山

在.Net Framework中动态创建类型---System.Reflection.Emit命名空间小试

 string assemblyName = this.txtAssemblyName.Text;
            
string className = this.txtClassName.Text;

            System.Diagnostics.Debug.Assert(assemblyName 
!= null && assemblyName != string.Empty);
            System.Diagnostics.Debug.Assert(className 
!= null && className != string.Empty);

            System.Reflection.AssemblyName asmName 
= new System.Reflection.AssemblyName(assemblyName);
            AssemblyBuilder asmBuilder 
= AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
            ModuleBuilder modBuilder 
= asmBuilder.DefineDynamicModule("MyModule"true);

            TypeBuilder typeBuilder 
= modBuilder.DefineType(className);
            typeBuilder.DefineField(
"myfield",typeof(string), System.Reflection.FieldAttributes.Public);
            MethodBuilder methodBuilder 
= typeBuilder.DefineMethod("CallMethod", System.Reflection.MethodAttributes.Public| System.Reflection.MethodAttributes.SpecialName | System.Reflection.MethodAttributes.HideBySig
                
                , 
nullnew Type[] { typeof(string) });

            methodBuilder.DefineParameter(
0, System.Reflection.ParameterAttributes.Retval, null);
            methodBuilder.DefineParameter(
1, System.Reflection.ParameterAttributes.In, "name");
            ILGenerator ilGenerator 
= methodBuilder.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ldarg_1);
            
//System.Reflection.Assembly asmSystem = System.Reflection.Assembly.GetAssembly(typeof(MessageBox));
            
//Type typeMessageBox = asmSystem.GetType("MessageBox");
            Type typeMessageBox = typeof(MessageBox);
            System.Reflection.MethodInfo mInfoShow 
= typeMessageBox.GetMethod("Show",new Type[]{typeof(string)}
                
//System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.Static,
                );

            ilGenerator.EmitCall(OpCodes.Call, mInfoShow, 
null);

            ilGenerator.Emit(OpCodes.Ret);

            Type customType 
= typeBuilder.CreateType();
            
object customeObj = Activator.CreateInstance(customType); ;

            System.Reflection.MethodInfo methodInfo 
= customType.GetMethod("CallMethod");
            
//customType.InvokeMember("CallMethod", System.Reflection.BindingFlags.Public, null, customeObj, new object[] { "123" });
            
//methodBuilder.Invoke(customeObj, new object[] { "123" });
            methodInfo.Invoke(customeObj, new object[] { "11" });
            Console.ReadLine();

posted on 2009-07-24 21:51 悟山 阅读(869) 评论(1)  编辑 收藏 引用

Feedback

# re: 在.Net Framework中动态创建类型---System.Reflection.Emit命名空间小试 2009-11-05 17:06 agri521

偶遇留言  回复  更多评论   



只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理