主要是:ide
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(); } }