简单反射练习
Posted 青墨淡潋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单反射练习相关的知识,希望对你有一定的参考价值。
主要是:
- 利用反射对实例进行构造;
- 以及调用实例的方法;
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Text; using System.Threading.Tasks; namespace AssemblyBuilder { class Program { public static Assembly ReadAssembly(string assemblyPath) { return Assembly.LoadFrom(assemblyPath); } public static Assembly ReadAssembly(Stream stream) { SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.ControlEvidence); securityPermission.Assert(); int num = (int)stream.Length; byte[] array = new byte[num]; stream.Read(array, 0, num); try { return Assembly.Load(array); } finally { CodeAccessPermission.RevertAssert(); } } public static Stream ReadAssemblyToStream(string assemblyPath) { FileStream fileStream = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Read); try { int num = (int)fileStream.Length; byte[] array = new byte[num]; fileStream.Read(array, 0, num); return new MemoryStream(array); } finally { fileStream.Close(); } } static void Main(string[] args) { Stream assemblyStream = ReadAssemblyToStream("./Lambda_Test.exe"); var assembly = ReadAssembly(assemblyStream); //使用 InvokeMember 调用构造函数初始化实例也可以 var programInstance = assembly.CreateInstance("FactoryMode.Program"); if (programInstance == null) { Console.WriteLine("There is no this type"); } else { var myType = programInstance.GetType(); Console.WriteLine("Type name is {0}", myType.ToString()); MethodInfo[] methods = myType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static); Console.WriteLine("Method number:{0}", methods.Length); foreach(var method in methods) { //怎样通过反射调用方法? if(method.Name == "NotMainMethod") { Console.WriteLine("Find method, name:{0}", method.Name); //没有实例直接用类型进行 InvokeMember 调用,需要调用类型的构造函数后再调用目标方法(前提示有定义构造函数),要带上 BindingFlags.CreateInstance //myType.InvokeMember("NotMainMethod", BindingFlags.Public | BindingFlags.CreateInstance, null, null, null); //使用已有实例时,就要指定 BindingFlags.Instance myType.InvokeMember("NotMainMethod", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, programInstance, null); //有实例则直接使用 method.Invoke(programInstance, null); } } } Console.ReadKey(); } } }
以上是关于简单反射练习的主要内容,如果未能解决你的问题,请参考以下文章