简单反射练习
主要是:
- 利用反射对实例进行构造;
- 以及调用实例的方法;
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(); } } }
12.2 补充构造实例:
public class TestObject { public string TestString1 { get; set; } public string TestString2 { get; set; } public TestObject() { } public TestObject(string testString1, string testString2) { TestString1 = testString1; TestString2 = testString2; } } class Program { static void Main(string[] args) { var tagType = typeof(TestObject); string[] paramArray = new string[] { "Hello", "World" }; Type[] typeArray = paramArray.Select(obj => obj.GetType()).ToArray(); ConstructorInfo constructor = tagType.GetConstructor(typeArray); var tagObject = (TestObject)constructor.Invoke(paramArray); Console.ReadLine(); } }