C# 以方括號 [Attribute] 標記類別/方法/屬性,提供編譯器或執行期額外資訊。
using System;
using System.Web.Services;
public class Utilities : WebService
{
[WebMethod]
public string GetTime()
{
return DateTime.Now.ToShortTimeString();
}
}
加上 [WebMethod],.NET 自動處理 XML/SOAP 交換。呼叫回傳:
<?xml version="1.0" encoding="utf-8"?> <string xmlns="https://tempuri.org/">7:26 PM</string>
using System;
[Serializable()]
public class Employee
{
public int ID;
public string Name;
[NonSerialized()] public int Salary; // 不序列化
}
Salary 雖為 public,但標記 [NonSerialized] 後不會被序列化。
可建立自訂 Attribute 擴展框架功能,詳細請參考官方文件。