如何使用C#/.NET反射在程序集中实例化类?
我要把这个库编译成calc.dll如何使用C#/.NET反射在程序集中实例化类?,c#,.net,reflection,invoke,instantiation,C#,.net,Reflection,Invoke,Instantiation,我要把这个库编译成calc.dll namespace MyClass { public class Calculator { public int Value1 {get; set;} public int Value2 {get; set;} public Calculator() { Value1 = 100; Value2 = 200; }
namespace MyClass
{
public class Calculator
{
public int Value1 {get; set;}
public int Value2 {get; set;}
public Calculator()
{
Value1 = 100;
Value2 = 200;
}
public int Add(int val1, int val2)
{
Value1 = val1; Value2 = val2;
return Value1 + Value2;
}
}
}
我想实例化Calculate类而不链接到calc.dll。C能做到吗?我提出了这段代码,但我不知道如何实例化计算器
类
using System;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
namespace EX
{
public class Code
{
public static void Test()
{
string path = Directory.GetCurrentDirectory();
string target = Path.Combine(path, @"./myclass.dll");
Assembly asm = Assembly.LoadFrom(target);
Calculator h = new Calculator(); // <-- ???
Type type = h.GetType();
MethodInfo m = type.GetMethod("Add");
int res = (int) m.Invoke(h, param);
Console.WriteLine("{0}", res);
}
public static void Main()
{
Test();
}
}
}
这是j探员的
string path = Directory.GetCurrentDirectory();
string target = Path.Combine(path, @"./myclass.dll");
Assembly asm = Assembly.LoadFrom(target);
Type type = asm.GetType("MyClass.Calculator");
ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes);
object calc = ctor.Invoke(null);
MethodInfo m = type.GetMethod("Add");
var param = new object[] {100, 200};
int res = (int) m.Invoke(calc, param);
Console.WriteLine("{0}", res);
它们都在工作,但我更喜欢Bala的解决方案,因为它比较短,通过CreateInstance
获取对象h
比让构造函数获取对象h(calc)
更直观
编辑:
看看这是否有效
Type calc = asm.GetType("MyClass.Calculator)";
object h = Activator.CreateInstance(calc);
如何在
m.Invoke(h,param)
中获取h
?@prosseek,`object calc=ctor.Invoke(null);MethodInfo m=type.GetMethod(“添加”);int res=(int)m.Invoke(计算,参数)`它可以编译,但我得到了未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例。在EX.Code.Test()处在EX.Code.Main()处
错误。@请参阅我的编辑。我从未使用过前面提到的重载。我对asm.FullName有点怀疑,但我使用了第二种方法,它应该可以工作。CreateInstance()
object h = Activator.CreateInstance(asm.FullName, "MyClass.Calculator");
Type calc = asm.GetType("MyClass.Calculator)"; object h = Activator.CreateInstance(calc);
string path = Directory.GetCurrentDirectory(); string target = Path.Combine(path, @"./myclass.dll"); Assembly asm = Assembly.LoadFrom(target); Type type = asm.GetType("MyClass.Calculator"); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); object calc = ctor.Invoke (null); MethodInfo m = type.GetMethod("Add"); int res = (int) m.Invoke(calc, param); Console.WriteLine("{0}", res);