VS2012 C#生成DLL并调用

1.建立一个C#工程生成DLL函数

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

项目建好后,为了理解,将项目中的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,功能是完成求两个数的最大公约数,代码以下:debug

 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.使用生成的dllcode

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

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

 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;it

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

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

在UseDll代码中,由于main函数须要用到参数,VS添加命令参数步骤以下:

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

截图以下:

相关文章
相关标签/搜索