1、先在VS里边创建一个类库(.Net Framework)(是2哦)
2、在项目里边添加你需要的内容
例如
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary2
{
public class Class1
{
public decimal Add(decimal x, decimal y)
{
long timer = System.DateTime.Now.Ticks;
int k = 0;
for (int i = 0; i < 100000000; i++)
{
k++;
}
long timer1 = System.DateTime.Now.Ticks;
Console.WriteLine(timer1 - timer);
return timer1 - timer;
}
public decimal SubTract(decimal x, decimal y)
{
return x - y;
}
public decimal Mul(decimal x, decimal y)
{
return x * y;
}
public decimal Div(decimal x, decimal y)
{
return x / y;
}
}
}
3、生成解决方案
4、新建一个控制台,然后把刚刚生成的解决方案放在新的项目的Debug下边。
5、在新建的项目中添加下边的内容,就可以调用里边的方法了。(这里提供了两个位置:一个是项目的Debug下边,一个是自己随意想放置的位置,都可以)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace TestDll0326
{
class Program
{
static void Main(string[] args)
{
//=================dll文件放到项目的Debug下边====================
//string path = "D:/Documents/Visual Studio 2017/Projects/TestDll0326/TestDll0326/bin/Debug/ClassLibrary2.dll";
//Assembly ass = Assembly.LoadFrom(path);
//Type type = ass.GetType("ClassLibrary2.Class1");
//MethodInfo mi1 = type.GetMethod("Add");
//Object obj = ass.CreateInstance("ClassLibrary2.Class1");
//object[] paramsValue = new object[2] { (decimal)5, (decimal)10 };
//mi1.Invoke(obj, paramsValue);
//MethodInfo mi2 = type.GetMethod("SubTract");
//mi2.Invoke(obj, paramsValue);
//MethodInfo mi3 = type.GetMethod("Mul");
//mi3.Invoke(obj, paramsValue);
//MethodInfo mi4 = type.GetMethod("Div");
//mi4.Invoke(obj, paramsValue);
//Console.WriteLine(mi1.Invoke(obj, paramsValue));
//Console.WriteLine(mi2.Invoke(obj, paramsValue));
//Console.WriteLine(mi3.Invoke(obj, paramsValue));
//Console.WriteLine(mi4.Invoke(obj, paramsValue));
//Console.ReadKey();
//=================dll文件放项目外边===================
string path = "C:/Users/Administrator/Desktop/NewFile/ClassLibrary2.dll";
Assembly ass = Assembly.LoadFrom(path);
Type type = ass.GetType("ClassLibrary2.Class1");
MethodInfo mi1 = type.GetMethod("Add");
Object obj = ass.CreateInstance("ClassLibrary2.Class1");
object[] paramsValue = new object[2] { (decimal)5, (decimal)10 };
mi1.Invoke(obj, paramsValue);
mi1.Invoke(obj, paramsValue);
mi1.Invoke(obj, paramsValue);
mi1.Invoke(obj, paramsValue);
mi1.Invoke(obj, paramsValue);
MethodInfo mi2 = type.GetMethod("SubTract");
mi2.Invoke(obj, paramsValue);
MethodInfo mi3 = type.GetMethod("Mul");
mi3.Invoke(obj, paramsValue);
MethodInfo mi4 = type.GetMethod("Div");
mi4.Invoke(obj, paramsValue);
//Console.WriteLine(mi1.Invoke(obj, paramsValue));
//Console.WriteLine(mi2.Invoke(obj, paramsValue));
//Console.WriteLine(mi3.Invoke(obj, paramsValue));
//Console.WriteLine(mi4.Invoke(obj, paramsValue));
Console.ReadKey();
}
}
}
6、完成以上,就可以啦,一定是.Net Framework库类哦。不然会报错的。