扩展方法可以在不修改原有类的代码前提下,给类“增加”一个方法。扩展方法虽然属于静态方法,但调用的语法却和对象调用类似。直接用一个例子来演示扩展方法。
首先,先准备一个类,这个类里面没有我们要扩展的方法:
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("这是一个扩展方法");