反射主要用于在程序运行期间动态解析相关类的类名,命名空间,属性,方法并进行相应操作,以下通过两个简单的例子进行了说明:
示例1:调用程序集内部方法,运行时动态获取相关类的信息,包括类名,命名空间等信息并进行对象的创建及方法的调用:
测试类:
class HI { public string Hi = "HelloWorld"; public string SayHello_CI() { return "Hello World!"; } public string SayHello_AC() { return "How are you!"; } }
调用类:
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Remoting; using System.Text; using System.Threading.Tasks; namespace ReflectionLearning01 { class Program { static void Main(string[] args) { Type type = typeof(HI); //Create object using Assembly Assembly Assem = type.Assembly; Object objAssembly = Assem.CreateInstance("ReflectionLearning01.HI", true); //Creare object using Activator ObjectHandle handler = Activator.CreateInstance(null, "ReflectionLearning01.HI"); Object objActvator = handler.Unwrap(); //Call the function in another class string res_ci = (string)type.InvokeMember("SayHello_CI", BindingFlags.InvokeMethod, null, objAssembly, null); string res_ac = (string)type.InvokeMember("SayHello_AC", BindingFlags.InvokeMethod, null, objActvator, null); string Name = type.Name; string FullName = type.FullName; string NameSpace = type.Namespace; var Assembly = type.Assembly; var Module = type.Module; Console.WriteLine("ClassName:" + Name); Console.WriteLine("ClassFullName:" + FullName); Console.WriteLine("NameSpace:" + NameSpace); Console.WriteLine("Assembly:" + Assembly); Console.WriteLine("Module:" + Module); Console.WriteLine(res_ci); Console.WriteLine(res_ac); Console.ReadLine(); } } }
运行结果:
示例2:在当前程序集内部调用外部程序集即动态加载DLL,调用其中的方法并返回方法返回值:
新建类库项目HelloWorld,新增类的详细代码如下,生成.dll:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelloWorld { public class HI { public string SayHello(string Hi) { return Hi+", current time is "+DateTime.Now.ToShortDateString()+",It‘s time to go home!"; } } }
新建类Windows 控制台程序ReflectionLearning,类的调用信息如下:
PS.不需要添加HelloWorld.dll到当前项目的引用中
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Remoting; using System.Text; using System.Threading.Tasks; namespace ReflectionLearning01 { class Program { static void Main(string[] args) { Assembly assembly = System.Reflection.Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "HelloWorld.dll"); Type type = assembly.GetType("HelloWorld.HI"); object instance = assembly.CreateInstance("HelloWorld.HI"); //Parameter list Type[] ParmType = new Type[1]; ParmType[0] = Type.GetType("System.String"); Object[] parm_obj = new Object[1]; parm_obj[0] = "HelloWorld!"; object result = type.GetMethod("SayHello", ParmType).Invoke(instance, parm_obj); Console.WriteLine(result); Console.ReadLine(); } } }
拷贝HelloWorld.dll到当前项目,并F5运行,调用成功后的信息如下所示:
到此,两个演示的例子已经完成,希望通过不断的使用,我们都能不断提高!
时间: 2024-10-25 00:35:09