Invoke methods using System.Reflection

Introduction

.NET provides mechnisms to compile source code and to use the generated assemblies within an application. Using these features you can make applications more adaptive and more flexible.

The follwing article shows how to invoke methods from an assembly using System.Reflection.

Necassary Using statements

Before you start add the following Using statements to your application to ease the use of the namespaces:

using System.Reflection;
using System.Security.Permissions; 

Getting started

At the beginning you have to know which method from which type and from which module you want to call. Inspecting an assembly can be done very easy with System.Reflection too. But now we assume having all the knowlegde about it, because we generated it ourselves like in Run-Time Code Generation Part I.

So we just set the module´s name, the type´s name and the method´s name:

string ModuleName = "TestAssembly.dll";
string TypeName = "TestClass";
string MethodName = "TestMethod";

Open an assembly

Then you can open the assembly and set some Binding Flags, which are necassary for the instanciation of the chosen type.

Assembly myAssembly = Assembly.LoadFrom(ModuleName);

BindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);

Invoke a method

After that three loops are used to inspect the assembly and get the chosen module/type/method combination. Within the last loop the type is instanciated and the method is called. The method can be called with parameters, but here we choose null for methods with no parameters. There can also be a response from the method, which we put into a general object.

Module [] myModules = myAssembly.GetModules();
foreach (Module Mo in myModules) 
    {
     if (Mo.Name == ModuleName) 
         {
         Type[] myTypes = Mo.GetTypes();
         foreach (Type Ty in myTypes)
             {
            if (Ty.Name == TypeName) 
                {
                MethodInfo[] myMethodInfo = Ty.GetMethods(flags);
                foreach(MethodInfo Mi in myMethodInfo)
                    {
                    if (Mi.Name == MethodName) 
                        {
                        Object obj = Activator.CreateInstance(Ty);
                        Object response = Mi.Invoke(obj, null);
                        }
                    }
                }
            }
        }
    }

Conclusion

With a few lines of code you make your application call any method in any type from any module. In combination with code compilation that is a powerful mechanism to enhance the adaptability of you applications.

About André Janus


I am currently student at the university of Karlsruhe and working on my master thesis at the IT-Management and Web Engineering Research Group within the institute of telematics.

Click here to view André Janus's online profile.

using CodeEditor.CodeEdit; using Microsoft.CSharp; using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CodeEditor { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void btnCompile_Click(object sender, EventArgs e) { //【1】新建C#代码生成器和代码编译器的实例 CodeDomProvider Provider = CodeDomProvider.CreateProvider("CSharp"); //【2】配置用于调用编译器的参数 CompilerParameters Parameters = new CompilerParameters(); Parameters.ReferencedAssemblies.Add("System.dll"); Parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); Parameters.ReferencedAssemblies.Add("System.Linq.dll"); Parameters.GenerateExecutable = false; Parameters.GenerateInMemory = true; //【3】启动编译 CompilerResults Result = Provider.CompileAssemblyFromSource(Parameters, rtbCode.Text); if (Result.Errors.HasErrors) { AppendInfo("编译错误:"); foreach (CompilerError err in Result.Errors) { AppendInfo(err.ErrorText); } } else { // 通过反射,调用实例 Assembly objAssembly = Result.CompiledAssembly; object objHelloWorld = objAssembly.CreateInstance("CodeEditor.CodeEdit.Code"); MethodInfo objMI = objHelloWorld.GetType().GetMethod("Test"); object ReValue = objMI.Invoke(objHelloWorld, null); AppendInfo(ReValue); } } //追加字符 private void AppendInfo(object Info) { rtbResult.Text =Info+"\n\r"; } } }
07-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值