首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 屬性系統:Attribute 裝飾類別與方法、WebMethod、Serializable 實戰應用

     編輯:關於C語言

屬性:宣告式中繼資料

C# 以方括號 [Attribute] 標記類別/方法/屬性,提供編譯器或執行期額外資訊。

WebMethod:一鍵發布 Web Service

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>

Serializable 與 NonSerialized:控制序列化行為

using System;

[Serializable()]
public class Employee
{
    public int ID;
    public string Name;
    [NonSerialized()] public int Salary; // 不序列化
}

Salary 雖為 public,但標記 [NonSerialized] 後不會被序列化。

自訂屬性

可建立自訂 Attribute 擴展框架功能,詳細請參考官方文件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved