VS2012 C#生成DLL并调用

1.创建一个C#工程生成DLL

 新建->项目->Visual C#->类库->MyMethods

项目建好后,为了理解,将项目中的Class1.cs 文件 重命名为 MySwap.cs,并在其中添加如下代码,代码功能就是交换两个数:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace MyMethods
 8 {
 9     public class MySwap
10     {
11         public static bool Swap(ref long i, ref long j)
12         {
13             i = i + j;
14             j = i - j;
15             i = i - j;
16             return true;
17         }
18     }
19 }

添加文件MyMaxCD.cs,功能是完成求两个数的最大公约数,代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace MyMethods
 8 {
 9      public class MaxCDClass
10      {
11           public static long MaxCD(long i, long j)
12           {
13                long a,b,temp;
14                if(i>j)
15                {
16                     a = i;
17                     b = j;
18                }
19                else
20                {
21                     b = i;
22                     a = j;
23                }
24                temp = a % b;
25                while(temp!=0)
26                {
27                     a = b;
28                     b = temp;
29                     temp = a % b;
30                }
31                return b;
32             }
33        }
34 }

然后点击生成解决方案,在项目debug目录下就有生成的dll文件。

2.使用生成的dll

新建->项目->Visual C#->控制台应用程序->UseDll

在program.cs文件中添加如下代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using MyMethods;
 7 namespace UseDll
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             if (args.Length != 2)
14             {
15 
16                 Console.WriteLine("Usage: MyClient <num1> <num2>");
17 
18                 return;
19 
20             }
21 
22             long num1 = long.Parse(args[0]);
23 
24             long num2 = long.Parse(args[1]);
25 
26             MySwap.Swap(ref num1, ref num2);
27 
28             // 请注意,文件开头的 using 指令使您得以在编译时使用未限定的类名来引用 DLL 方法
29 
30             Console.WriteLine("The result of swap is num1 = {0} and num2 ={1}", num1, num2);
31 
32 
33 
34             long maxcd = MaxCDClass.MaxCD(num1, num2);
35 
36 
37 
38             Console.WriteLine("The MaxCD of {0} and {1} is {2}", num1, num2, maxcd); 
39 
40         }
41     }
42 }

注意代码中要引入using MyMethods;

到此还需要将刚才生成的dll文件引入工程:

UseDLL右键->添加引用->浏览 选择刚才生成的dll所在路径 ok;

在UseDll代码中,因为main函数需要用到参数,VS添加命令参数步骤如下:

UseDll右键->属性->调试->命令行参数 我在这里输入44 33(注意参数之间不需要逗号)

截图如下:

原文地址:https://www.cnblogs.com/LCCRNblog/p/3691704.html