惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

罗磊的独立博客
Cisco Talos Blog
Cisco Talos Blog
C
Check Point Blog
博客园_首页
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Martin Fowler
Martin Fowler
Recorded Future
Recorded Future
S
Security @ Cisco Blogs
L
LINUX DO - 最新话题
博客园 - 司徒正美
P
Privacy International News Feed
G
Google Developers Blog
I
Intezer
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
C
Cybersecurity and Infrastructure Security Agency CISA
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Scott Helme
Scott Helme
K
Kaspersky official blog
I
InfoQ
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
Webroot Blog
Webroot Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
大猫的无限游戏
大猫的无限游戏
D
Docker
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Microsoft Azure Blog
Microsoft Azure Blog
Spread Privacy
Spread Privacy
量子位
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
SecWiki News
SecWiki News
S
Security Affairs
Latest news
Latest news
人人都是产品经理
人人都是产品经理
C
CERT Recently Published Vulnerability Notes
S
Security Archives - TechRepublic
V
Visual Studio Blog
T
Troy Hunt's Blog
S
Secure Thoughts
F
Fortinet All Blogs
V
V2EX
The Register - Security
The Register - Security
J
Java Code Geeks
MongoDB | Blog
MongoDB | Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

博客园 - 王庆

crosstool-ng搭建交叉编译环境注意事项 多重继承及虚继承中对象内存的分布 编写和调试Android下JNI程序流程 eclipse xml文件中按alt+/没有提示信息 Android NDK 工具链的使用方法(Standalone Toolchain) 编译Android VNC Server 使用gdb和gdbserver调试Android C/C++程序 openssl在多平台和多语言之间进行RSA加解密注意事项 LINUX开发使用的3个远程工具 NDK 链接第三方静态库的方法 关于线程池的一段代码 理解ParseChildren用法 快速查找ASP.NET产生的临时文件 捕获ASP.NET程序发生的异常 Synchronized vs SyncRoot Exception vs ApplicationException 【转】Hashtable,ListDictionary,HybridDictionary比较 Monitor用法 C#多线程之Thread
动态生成程序集和类型
王庆 · 2009-02-21 · via 博客园 - 王庆

using System;
using System.Data;
using System.Reflection;
using System.Reflection.Emit;
namespace ConsoleApplicationReflection
{
    
class ClassBuilder
    {
        
/// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>
        [STAThread]
        
static void Main(string[] args)
        {
            
try
            {
                Console.WriteLine(
"Enter values:");
                
string numbers = Console.ReadLine();
                
string[] values = numbers.Split(',');
                
//生成一个类型,其中包含一个方法(ReturnSum),返回两数相加的结果
                Type ClsType = CreateType("OurAssembly""OurModule""MathOps""ReturnSum");//基于反射,生成类型(MathOps)实例
                object ClsTypeInstance = Activator.CreateInstance(ClsType);
                
//基于反射,查找类型(MathOps)中的方法(ReturnSum)
                MethodInfo mi = ClsType.GetMethod("ReturnSum");
                
//方法需要的参数数组
                object[] objs = new object[] { Int32.Parse(values[0].ToString()), Int32.Parse(values[1].ToString()) };
                
//执行方法
                object obj = mi.Invoke(ClsTypeInstance, objs);//下面2行代码和上面4行执行的结果一样
                
//object ClsTypeInstance = Activator.CreateInstance(ClsType);
                
//object obj = MathOpsClass.InvokeMember("ReturnSum", BindingFlags.InvokeMethod, null, ClsTypeInstance, new object[] { Int32.Parse(values[0].ToString()), Int32.Parse(values[1].ToString()) });

                Console.WriteLine(
"Sum: {0}", obj.ToString());
            }
            
catch (Exception ex)
            {
                Console.WriteLine(
"An error occured: {0}", ex.Message);
            }

            Console.ReadLine();
        }

/// <summary>
        
/// 动态生成程序集和类型
        
/// </summary>
        
/// <param name="assemblyName">程序集名称</param>
        
/// <param name="moduleName">模块名称</param>
        
/// <param name="className">类型名称</param>
        
/// <param name="methodName">方法名称</param>
        
/// <returns></returns>
        public static Type CreateType(string assemblyName, string moduleName, string className, string methodName)
        {
            
try
            {
                AssemblyName name 
= new AssemblyName();
                name.Name 
= assemblyName;

                AppDomain domain 

= System.Threading.Thread.GetDomain();

                AssemblyBuilder assBuilder 

= domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);

                ModuleBuilder mb 

= assBuilder.DefineDynamicModule(moduleName);

                TypeBuilder theClass 

= mb.DefineType(className, TypeAttributes.Public | TypeAttributes.Class);
                
//方法返回值类型
                Type rtnType = typeof(int);
                
//方法参数类型
                Type[] param = new Type[2];
                param[
0= typeof(System.Int32);
                param[
1= typeof(System.Int32);
                
//定义方法签名
                MethodBuilder method = theClass.DefineMethod(methodName, MethodAttributes.Public, rtnType, param);//定义方法实体
                ILGenerator gen = method.GetILGenerator();
                gen.DeclareLocal(
typeof(int));  //.locals init ([0] int32 c)
                gen.Emit(OpCodes.Ldarg_1);      //IL_0000:  ldarg.1
                gen.Emit(OpCodes.Ldarg_2);      //IL_0001:  ldarg.2
                gen.Emit(OpCodes.Add);          //IL_0002:  add
                gen.Emit(OpCodes.Stloc_0);      //IL_0003:  stloc.0
                gen.Emit(OpCodes.Ldloc_0);      //IL_0004:  ldloc.0
                gen.Emit(OpCodes.Ret);          //IL_0005:  ret//返回生成的类型
                return theClass.CreateType();
            }
            
catch (Exception ex)
            {
                Console.WriteLine(
"An error occured: {0}", ex.Message);
                
return null;
            }
        }

    }
}