【发布时间】:2019-05-07 16:33:39
【问题描述】:
我在 .NET Framework 中创建了一个 dll,现在在另一个项目中使用它。我找到了两种使用我的 dll 的方法。
通过在我的项目引用中引用 dll 并创建实例
使用反射
我的 DLL
namespace MathHelper
{
public class Helper
{
public int add(int a, int b)
{
return a + b;
}
}
}
我的程序
static void Main(string[] args)
{
//Using referenced dll in project
Helper helper = new Helper();
Console.WriteLine(helper.add(4,5));
//Using Reflection
Assembly assembly = Assembly.LoadFile(@"C:\Users\myUser\source\repos\TestMathHelper\TestMathHelper\bin\Debug\MathHelper.dll");
Type type = assembly.GetType("MathHelper.Helper");
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("add");
int result = (int)method.Invoke(instance, new object[] {4, 5});
Console.WriteLine(result);
Console.ReadKey();
}
两个结果都有效并显示 9.
我应该更喜欢哪种方法? 什么时候应该使用反射,什么时候不应该? 反射的优点是什么?
【问题讨论】:
-
经验法则:仅当其他更简单(和/或更快)的方法不可行时才使用反射。永远记住:你的目标应该是编写可读、可维护的代码。自己提问并回答:您在问题中概述的两种方法中的哪一种会产生更好的可读性和更好的可维护性源代码? (顺便说一句,可维护性不仅包括未来对源代码的扩展/修改,还包括调试和故障排除代码的能力/简单性)
-
哪种方法更方便,代码更少?看起来这是第一个 - 参考。
标签: c# dll reflection .net-assembly