1. 程式人生 > >C# DLL(程式集)的生成和呼叫

C# DLL(程式集)的生成和呼叫

日期:2018年11月24日

環境:Window 10,VS2015

一、利用VS2015自帶的工具生成DLL

  步驟:

  1.利用C#準備一個.cs檔案;

 1 using System;
 2 
 3 public class MyMath
 4 {
 5     public MyMath()
 6     {
 7         Console.WriteLine("This is DLL!!!");
 8     }
 9     public long Add(long a,long b)
10     {
11         return (a + b);
12     }
13 }
  2.開始選單->Visual Studio 2015->VS2015 開發人員命令提示;

  

  3.輸入csc /t:library /out:C:\Users\xxxxx\Desktop\study\AcmeCollections\AcmeCollections\MyMath.dll C:\Users\xxxxx\Desktop\study\AcmeCollections\AcmeCollections\MyMath.cs;

  註解:

    1)library:意思是編譯成類庫,否則必須有Main();

    2)/out:C:\Users\xxxxx\Desktop\study\AcmeCollections\AcmeCollections\MyMath.dll:輸出檔案的位置和名稱;

    3)C:\Users\xxxxx\Desktop\study\AcmeCollections\AcmeCollections\MyMath.cs:原始檔的位置和名稱;

    

    上圖沒有出現報錯,即操作成功;

二、給你的專案新增引用此DLL,並執行;

   

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using
System.Runtime.InteropServices; 7 8 namespace AcmeCollections 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 long ans; 15 string str; 16 MyMath myMath = new MyMath(); 17 ans = myMath.Add(1, 2); 18 str = Convert.ToString(ans); 19 Console.WriteLine(str); 20 Console.ReadLine(); 21 } 22 } 23 }
Main Code

  執行結果:

    

三、參考連結

  1.https://www.cnblogs.com/zuoguanglin/archive/2012/02/23/2364613.html

  2.https://docs.microsoft.com/zh-cn/dotnet/csharp/tour-of-csharp/program-structure