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(注意參數之間不需要逗號)

截圖如下:

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM