如何在C#/.NET中使用反射来实例化程序集中的类
本文关键字:程序 实例化 程序集 集中 反射 NET | 更新日期: 2023-09-27 18:00:13
我有这个库要编译到calc.dll。
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#能做到吗?我想出了这段代码,但我不知道如何实例化Calculator
类。
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();
}
}
}
已添加
我有两个解决方案,一个来自Bala R
var param = new object[] {100, 200};
string path = Directory.GetCurrentDirectory();
string target = Path.Combine(path, @"./myclass.dll");
Assembly asm = Assembly.LoadFrom(target);
Type calc = asm.GetType("MyClass.Calculator");
object h = Activator.CreateInstance(calc);
MethodInfo m = calc.GetMethod("Add");
int res = (int) m.Invoke(h, param);
Console.WriteLine("{0}", res);
这个来自代理-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的解决方案,因为它更短,从object h
到CreateInstance
比从构造函数到object h(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);
object h = Activator.CreateInstance(asm.FullName, "MyClass.Calculator");
编辑:
看看这是否有效
Type calc = asm.GetType("MyClass.Calculator)";
object h = Activator.CreateInstance(calc);