程序集(Assembly)
程序集是 .NET 應用程序的基本構建模塊。它可以是 DLL(動態鏈接庫)或 EXE(可執行文件)文件。程序集包含類型和資源,可以被其他程序集引用和使用。
開發 DLL(動態鏈接庫)是 C# 開發中的一個常見任務。DLL 文件允許你將代碼模塊化並在多個應用程序中重用。以下是創建和使用 DLL 的步驟:
創建 DLL 專案
步驟 1:創建一個類庫專案
- 打開 Visual Studio。
- 選擇 "Create a new project"。
- 在項目模板中選擇 "Class Library"(.NET Core 或 .NET Framework,根據你的需求)。
- 為你的項目命名並選擇保存位置。
- 點擊 "Create"。
步驟 2:編寫代碼
在新創建的專案中,會自動生成一個類文件(如Class1.cs
)。你可以添加自己的類和方法。namespace MyLibrary
{
public class MathHelper
{
public int Add(int a, int b)
{
return a + b;
}
}
}
步驟 3:構建專案
- 在 Visual Studio 中,右鍵單擊解決方案資源管理器中的專案名稱。
- 選擇 "Build" 或 "Rebuild"。
- 構建成功後,DLL 文件將在專案的
bin\Debug\netstandard2.0\
或bin\Debug\netcoreapp2.0\
(具體路徑取決於你的目標框架)目錄中生成。
使用 DLL
要在其他應用程序中使用剛才創建的 DLL,需要將其引用到你的新項目中。
步驟 1:創建一個主控台應用程序
- 打開 Visual Studio。
- 創建一個新的專案,選擇 "Console App" 模板。
- 為你的應用命名並選擇保存位置。
步驟 2:添加 DLL 引用
- 在主控台應用程序中,右鍵單擊 "References"。
- 選擇 "Add Reference..."。
- 在左側菜單中選擇 "Browse",並導航到之前生成的 DLL 文件位置。
- 選擇 DLL 文件並添加引用。
步驟 3:使用 DLL 中的類和方法
在你的主控台應用程序中使用從 DLL 引用的類和方法。
using System;
using MyLibrary;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
MathHelper mathHelper = new MathHelper();
int result = mathHelper.Add(5, 3);
Console.WriteLine($"5 + 3 = {result}");
}
}
}
補充說明
通過創建類庫專案、編寫代碼並構建 DLL,你可以生成可重用的組件。在其他應用程序中引用和使用這些 DLL 可以提高代碼的模塊化和可重用性。這種方法在大型軟件開發中尤其有用,因為它可以將不同功能分離到獨立的組件中。
命名空間(Namespace)
命名空間用於組織類型,並防止名稱衝突。命名空間可以包含類、接口、枚舉和其他命名空間。
using System;
namespace MyApplication
{
namespace Utilities
{
public class UtilityClass
{
public static void PrintMessage(string message)
{
Console.WriteLine(message);
}
}
}
class Program
{
static void Main(string[] args)
{
Utilities.UtilityClass.PrintMessage("Hello, World!");
}
}
}
NuGet 包管理器
NuGet 是 .NET 的包管理器,用於查找、安裝和管理外部庫和依賴項。使用 NuGet,可以輕鬆地將第三方庫添加到你的 C# 項目中,類似於 Python 中的 pip。
使用 NuGet 安裝包
- 在 Visual Studio 中使用 NuGet:
- 右鍵單擊項目,選擇“Manage NuGet Packages”。
- 搜索所需的包,然後點擊“Install”進行安裝。
- 使用命令行:在項目目錄中運行以下命令:
dotnet add package <PackageName>
示例:使用 Newtonsoft.Json 解析 JSON
這是一個常見的例子,展示如何使用 NuGet 安裝並使用外部包。在這裡,我們使用 Newtonsoft.Json
來解析 JSON。
- 安裝 Newtonsoft.Json:
dotnet add package Newtonsoft.Json
- 使用 Newtonsoft.Json 解析 JSON:
using System;
using Newtonsoft.Json;
public class Program
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void Main(string[] args)
{
string json = "{\\\\"Name\\\\":\\\\"Alice\\\\",\\\\"Age\\\\":30}";
// 解析 JSON 字符串
Person person = JsonConvert.DeserializeObject<Person>(json);
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
這個示例展示了如何使用 NuGet 安裝和引用第三方庫,以及如何使用該庫來解析 JSON 字符串。通過這種方式,C# 可以輕鬆地擴展和使用大量的現有庫來滿足不同的需求。