首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> C# 入門

C++ 轉 C# 進階必讀(四):網路串流、屬性與反射

     編輯:C# 入門

TCP/IP 網路串流操作

.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}");
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved