此篇將介紹C#如何在運行時動態調用方法。當某些類型是運行時動態肯定時,編譯時的靜態編碼是沒法解決這些動態對象或類的方法調用的。此篇則給你一把利劍,讓動態對象的方法調用成爲可能。ide
1.動態調用dll裏的方法
編碼
- <span style="font-family:SimSun;font-size:12px;">
- class Class1
- {
- public static string method1()
- {
- return "I am Static method (method1) in class1";
- }
- public string method2()
- {
- return "I am a Instance Method (method2) in Class1";
- }
- public string method3(string s)
- {
- return "Hello " + s;
- }
- }
-
- class DynamicInvoke
- {
- public static void Main(string[] args)
- {
-
- string path = "Class1.dll";
- Assembly assembly = Assembly.Load(path);
-
-
- Type type = assembly.GetType("Class1");
-
-
- string str = (string)type.InvokeMember("method1", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] { });
- Console.WriteLine(str);
-
-
- object o = Activator.CreateInstance(type);
- str = (string)type.InvokeMember("method2", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, new object[] { });
- Console.WriteLine(str);
-
-
- object[] par = new object[] { "kunal" };
- str = (string)type.InvokeMember("method3", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, par);
- Console.WriteLine(str);
-
-
-
- var arguments = new object[] { str, null };
- typeof(int).InvokeMember("TryParse", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static,
- null, null, arguments);
- Console.WriteLine(arguments[1]);
- }
- }</span>
2.動態加載類文件並調用方法:spa
- <span style="font-family:SimSun;font-size:12px;">using System;
- using System.CodeDom.Compiler;
- using System.IO;
- using System.Reflection;
- using System.Threading;
- using System.Windows.Forms;
- using Microsoft.CSharp;
-
- namespace _32.DynamicReflection
- {
- internal class Program
- {
- private static void Main(string[] args)
- {
- #region 內置標籤方法 (動態加載)
-
- const string className = "DynamicReflection.Test";
- string fileName = <strong>Thread.GetDomain().BaseDirectory + "Test.cs";</strong>
-
- if (File.Exists(fileName))
- {
- var sourceFile = new FileInfo(fileName);
- CodeDomProvider provider = new CSharpCodeProvider();
- var cp = new CompilerParameters();
- cp.ReferencedAssemblies.Add("System.dll");
-
- cp.GenerateExecutable = false;
- cp.GenerateInMemory = true;
- cp.TreatWarningsAsErrors = false;
-
-
- CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile.FullName);
- if (cr.Errors.Count < 1)
- {
- Assembly asm = cr.CompiledAssembly;
-
-
- Type type = asm.GetType(className);
- var str =(string)type.InvokeMember("SayHello1", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] {});
- Console.WriteLine(str);
-
-
- object instance = asm.CreateInstance(className);
- str =(string)type.InvokeMember("SayHello2", BindingFlags.Default | BindingFlags.InvokeMethod, null, instance,new object[] {});
- Console.WriteLine(str);
-
-
- var par = new object[] {"zhangqs008"};
- str =(string)type.InvokeMember("SayHello3", BindingFlags.Default | BindingFlags.InvokeMethod, null, instance,par);
- Console.WriteLine(str);
-
- Console.Read();
- }
- else
- {
- string msg = null;
- for (int index = 0; index < cr.Errors.Count; index++)
- {
- CompilerError error = cr.Errors[index];
- msg += "【錯誤" + (index + 1) + "】" + Environment.NewLine;
- msg += "[文件] " + error.FileName + Environment.NewLine;
- msg += "[位置] 行" + error.Line + ",列" + error.Column + Environment.NewLine;
- msg += "[信息] " + error.ErrorText + Environment.NewLine;
- msg += Environment.NewLine;
- }
- MessageBox.Show(msg, "內置方法類編譯錯誤");
- }
- }
-
- #endregion
- }
- }
- }</span>
類文件:.net
- <span style="font-family:SimSun;font-size:12px;">namespace DynamicReflection
- {
- public class Test
- {
- public static string SayHello1()
- {
- return "hello static method";
- }
-
- public string SayHello2()
- {
- return "hello instance method";
- }
-
- public string SayHello3(string args)
- {
- return "hello args " + args;
- }
- }
- }
- </span>