c#擴充方法

來源:互聯網
上載者:User

標籤:public   set   rac   sum   示範   his   屬性   style   靜態   

擴充方法可以在不修改原有類的代碼前提下,給類“增加”一個方法。擴充方法雖然屬於靜態方法,但調用的文法卻和對象調用類似。直接用一個例子來示範擴充方法。

首先,先準備一個類,這個類裡面沒有我們要擴充的方法:

public class Card{    private Chow chow;  //吃牌屬性    private Pong pong;    //碰牌屬性    private Kong kong;  //明杠牌屬性    private UnKong unKong;  //暗杠屬性    private CardCtrl cardCtrl;    private readonly int weight;       //牌的權值    private CardType.CharacterType belongto;  //角色類型/// <summary>/// 構造一張card/// </summary>/// <param name="Weight">哪張牌</param>/// <param name="Belongto">屬於誰</param>/// <param name="cardCtrl">cardCtrl的引用</param>    public Card(int Weight,CardType.CharacterType Belongto, CardCtrl cardCtrl)    {        weight = Weight;        belongto = Belongto;        this.cardCtrl = cardCtrl;    }/// <summary>/// 設定chow,返回chow/// </summary>    public Chow Chow    {        set { chow = value; }        get { return chow; }    }/// <summary>/// 設定pong,返回pong/// </summary>    public Pong Pong    {        set { pong = value; }        get { return pong; }    }    /// <summary>    /// 設定exposed,返回exposed    /// </summary>    public Kong Kong    {        set { kong = value; }        get { return kong; }    }   /// <summary>    /// 設定 CardCtrl 返回CardCtrl    /// </summary>    public CardCtrl CardCtrl    {       set       {         //  GameObject.Destroy(cardCtrl.transform.parent.gameObject);           cardCtrl = value;       }        get { return cardCtrl; }    }    /// <summary>    /// 返回牌的權值    /// </summary>    public int  GetCardWeight    {        get { return weight; }    }    /// <summary>    /// 牌的歸屬    /// </summary>    public CardType.CharacterType Attribution    {        set { belongto = value; }        get { return belongto; }    }}

然後,再準備以後靜態類,靜態類裡面有一個靜態方法,對我們要擴充的類增加擴充方法:

SayHello就是我們擴充的方法,參數是我們要擴充的類,用this標註。

public static class nnn
{
public static void SayHello(this Card card)
{
Debug.Log("這是一個擴充方法");

c#擴充方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.