
正文
VS2012 C#生成DLL并调用
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
1.创建一个C#工程生成DLL
新建->项目->Visual C#->类库->MyMethods
项目建好后,为了理解,将项目中的Class1.cs 文件 重命名为 MySwap.cs,并在其中添加如下代码,代码功能就是交换两个数:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MyMethods
{
public class MySwap
{
public static bool Swap(ref long i, ref long j)
{
i = i + j;
j = i - j;
i = i - j;
return true;
}
}
}
添加文件MyMaxCD.cs,功能是完成求两个数的最大公约数,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MyMethods
{
public class MaxCDClass
{
public static long MaxCD(long i, long j)
{
long a,b,temp;
if(i>j)
{
a = i;
b = j;
}
else
{
b = i;
a = j;
}
temp = a % b;
while(temp!=)
{
a = b;
b = temp;
temp = a % b;
}
return b;
}
}
}
然后点击生成解决方案,在项目debug目录下就有生成的dll文件。
2.使用生成的dll
新建->项目->Visual C#->控制台应用程序->UseDll
在program.cs文件中添加如下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyMethods;
namespace UseDll
{
class Program
{
static void Main(string[] args)
{
if (args.Length != )
{ Console.WriteLine("Usage: MyClient <num1> <num2>"); return; } long num1 = long.Parse(args[]); long num2 = long.Parse(args[]); MySwap.Swap(ref num1, ref num2); // 请注意,文件开头的 using 指令使您得以在编译时使用未限定的类名来引用 DLL 方法 Console.WriteLine("The result of swap is num1 = {0} and num2 ={1}", num1, num2); long maxcd = MaxCDClass.MaxCD(num1, num2); Console.WriteLine("The MaxCD of {0} and {1} is {2}", num1, num2, maxcd); }
}
}
注意代码中要引入using MyMethods;
到此还需要将刚才生成的dll文件引入工程:
UseDLL右键->添加引用->浏览 选择刚才生成的dll所在路径 ok;
在UseDll代码中,因为main函数需要用到参数,VS添加命令参数步骤如下:
UseDll右键->属性->调试->命令行参数 我在这里输入44 33(注意参数之间不需要逗号)
截图如下:








