当前位置: 首页 > 编程语言 > C#

如何在C#-.NET中使用反射在程序集中实例化类?Share

时间:2023-04-11 10:36:03 C#

如何在C#/.NET中使用反射实例化程序集中的类?我将这个库编译为calc.dll。namespaceMyClass{publicclassCalculator{publicintValue1{get;设置;}publicintValue2{get;设置;}公共计算器(){值1=100;值2=200;}publicintAdd(intval1,intval2){Value1=val1;值2=val2;返回值1+值2;我想在不链接到calc.dll的情况下实例化Calculate类。C#可以吗?我想出了这段代码,但我不知道如何实例化计算器类。使用系统;使用System.IO;使用System.Reflection;使用系统诊断;使用System.Collections.Generic;namespaceEX{publicclassCode{publicstaticvoidTest(){stringpath=Directory.GetCurrentDirectory();stringtarget=Path.Combine(path,@"./myclass.dll");组装asm=Assembly.LoadFrom(target);计算器h=new计算器();//<--???输入类型=h.GetType();MethodInfom=type.GetMethod("添加");intres=(int)m.Invoke(h,参数);Console.WriteLine("{0}",res);}publicstaticvoidMain(){测试();}}}添加我有两个解决方案,一个来自BalaR.varparam=newobject[]{100,200};字符串路径=Directory.GetCurrentDirectory();stringtarget=Path.Combine(path,@"./myclass.dll");组装asm=Assembly.LoadFrom(target);输入calc=asm.GetType("MyClass.Calculator");对象h=Activator.CreateInstance(calc);MethodInfom=calc.GetMethod("添加");intres=(int)m.Invoke(h,参数);Console.WriteLine("{0}",资源);这是来自agent-jstringpath=Directory.GetCurrentDirectory();stringtarget=Path.Combine(path,@"./myclass.dll");组装asm=Assembly.LoadFrom(target);输入type=asm.GetType("MyClass.Calculator");ConstructorInfoctor=type.GetConstructor(Type.EmptyTypes);objectcalc=ctor.Invoke(null);MethodInfom=type.GetMethod("添加");varparam=newobject[]{100,200};intres=(int)m.Invoke(calc,param);Console.WriteLine("{0}",res);它们都有效,但我更喜欢Bala的解决方案,因为它更短,通过CreateInstance获取对象h比通过构造函数获取对象h(calc)更直观objecth=Activator.CreateInstance(asm.FullName,"MyClass.Calculator");编辑:看看这是否有效以上是C#学习教程:HowtoinstantiateaclassinanassemblyusingReflectionwithC#/.NET?如果分享的内容对你有用,需要了解更多C#学习教程,希望大家多多关注——Typecalc=asm.GetType("MyClass.Calculator)";对象h=Activator.CreateInstance(calc);字符串路径=Directory.GetCurrentDirectory();stringtarget=Path.Combine(path,@"./myclass.dll");组装asm=Assembly.LoadFrom(target);输入type=asm.GetType("MyClass.Calculator");ConstructorInfoctor=type.GetConstructor(Type.EmptyTypes);objectcalc=ctor.Invoke(null);MethodInfom=type.GetMethod("添加");intres=(int)m.Invoke(calc,param);Console.WriteLine("{0}",res);本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢