組件是 .NET 部署、版本控制、安全性與類型標識的基本單位。以 .dll 或 .exe 形式存在,包含:
csc /target:library /out:WebRequest.dll /reference:System.Net.dll WebRequest.cs
/target:library:產生 DLL 而非 EXE(無需 Main 入口點)。/reference (或 /r):引用相依組件。/out:指定輸出檔名。.dll。using System;
using System.Net;
using System.IO;
using System.Text;
namespace Presenting.CSharp
{
public class RequestWebPage
{
private const int BufferSize = 128;
private string _url;
public RequestWebPage() { }
public RequestWebPage(string url) => _url = url;
public string Url
{
get => _url;
set => _url = value;
}
public void GetContent(out string content)
{
if (string.IsNullOrEmpty(_url))
throw new ArgumentException("URL must be provided.");
var request = WebRequest.Create(_url);
using var response = request.GetResponse();
using var stream = response.GetResponseStream();
var buffer = new byte[BufferSize];
var builder = new StringBuilder();
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, BufferSize)) > 0)
{
builder.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
}
content = builder.ToString();
}
}
}
WebResponse/Stream 確定性釋放。using System;
using Presenting.CSharp; // 引入命名空間
class TestClient
{
static void Main()
{
var wrq = new RequestWebPage("https://example.com");
try
{
wrq.GetContent(out string html);
Console.WriteLine(html.Substring(0, Math.Min(500, html.Length)));
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
csc /reference:WebRequest.dll TestClient.cs
namespace MyCompany.MyProduct.Module
{
public class MyClass { }
}
<Company>.(<Product>|<Technology>)<Feature>.<SubNamespace>
Microsoft.AspNetCore.Mvc、Contoso.Payroll.TaxCalculationSystem、Microsoft 開頭)。// File1.cs
namespace Presenting.CSharp { public class WhoisLookup { ... } }
// File2.cs
namespace Presenting.CSharp { public class RequestWebPage { ... } }
編譯單一組件:
csc /target:library /out:Presenting.CSharp.dll /reference:System.Net.dll WhoisLookup.cs RequestWebPage.cs
| 修飾符 | 組件內 | 組件外 (引用者) |
|---|---|---|
public | ✅ | ✅ |
internal (預設) | ✅ | ❌ |
private | 僅類別內 | ❌ |
protected internal | ✅ | 僅衍生類 |
組件邊界是 internal 的終點。設計原則:預設 internal,僅公開必要 API (public)。
| 類型 | 部署位置 | 版本控制 | 命名要求 |
|---|---|---|---|
| 私有組件 | 應用程式目錄 (同目錄或子目錄) | 無 (以檔案為準) | 簡單名稱即可 |
| 共用組件 | 全域組件快取 (GAC) | 強名稱 (強式名稱):名稱+版本+文化特性+公開金鑰語彙 | 必須強名稱簽署 |
sn -k MyKey.snk.snk。csc /keyfile:MyKey.snl /target:library ...gacutil /i MyAssembly.dll (需管理員權限)。<Major>.<Minor>.<Build>.<Revision>
組件繫結重導向 (bindingRedirect in app.config) 可解決版本衝突。
netstandard2.0 或 net6.0 等,獲得跨平台復用能力。PackageReference 管理 NuGet 相依性,取代 GAC。dotnet pack),內建版本管理與相依解析。Nullable、GenerateDocumentationFile 提升 API 可用性。public),其餘 internal。IDisposable、非同步方法、取消權杖等現代模式。///) 覆蓋所有公共 API。