.NET 將網路通訊封裝為串流模型,伺服器端:
TcpListener listener = new TcpListener(65000);
listener.Start();
Socket clientSocket = listener.Accept(); // 同步等待連線
NetworkStream netStream = new NetworkStream(clientSocket);
StreamWriter writer = new StreamWriter(netStream);
writer.WriteLine("資料傳送至客戶端");
writer.Flush();
客戶端:
TcpClient client = new TcpClient("localhost", 65000);
NetworkStream netStream = client.GetStream();
StreamReader reader = new StreamReader(netStream);
string line;
while ((line = reader.ReadLine()) != null)
Console.WriteLine(line);
屬性提供聲明式中繼資料,編譯時嵌入組件:
[Serializable]、[Obsolete]、[assembly: AssemblyVersion("1.0")]。System.Attribute,可標記類別、方法、欄位等目標。[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class BugFixAttribute : Attribute
{
public int BugID { get; }
public string Programmer { get; }
public string Date { get; }
public string Comment { get; set; } // 命名參數
public BugFixAttribute(int bugID, string programmer, string date)
{ BugID = bugID; Programmer = programmer; Date = date; }
}
// 使用範例
[BugFix(123, "Jesse", "2024-01-01", Comment = "Off-by-one error")]
public class MyClass { }
typeof(MyClass) 或 Type.GetType("Full.Name") 取得 Type 物件。GetCustomAttributes 讀取屬性中繼資料。Assembly.Load 動態載入組件,GetTypes() 列舉所有型別。Activator.CreateInstance + MethodInfo.Invoke 實現動態建構與呼叫。Type mathType = Type.GetType("System.Math");
object instance = Activator.CreateInstance(mathType);
MethodInfo cosMethod = mathType.GetMethod("Cos", new[] { typeof(double) });
object result = cosMethod.Invoke(instance, new object[] { 45.0 });
Console.WriteLine($"Cos(45) = {result}");