Extension methods can "add" a method to a class without modifying the original class's code. Although the extension method is static, the syntax of the call is similar to the object invocation. The extension method is demonstrated directly using an example.
First, prepare a class in which there is no method we want to extend:
Public classcard{PrivateChow Chow;//Eat Card Properties PrivatePong Pong;//Touch Card Properties PrivateKong Kong;//Ming Bar Properties PrivateUnkong Unkong;//Dark Bar Property PrivateCardctrl Cardctrl; Private ReadOnly intWeight//the right value of the card PrivateCardtype.charactertype belongto;//Role Type/// <summary>///construct a card/// </summary>/// <param name= "Weight" >which card?</param>/// <param name= "Belongto" >belong to who</param>/// <param name= "Cardctrl" >references to Cardctrl</param> PublicCard (intweight,cardtype.charactertype belongto, Cardctrl Cardctrl) {Weight=Weight; Belongto=belongto; This. Cardctrl =Cardctrl; }/// <summary>///set Chow, return Chow/// </summary> PublicChow Chow {Set{Chow =value;} Get{returnChow;} }/// <summary>///set Pong, return Pong/// </summary> PublicPong Pong {Set{Pong =value;} Get{returnPong;} } /// <summary> ///set exposed, return exposed/// </summary> PublicKong Kong {Set{Kong =value;} Get{returnKong;} } /// <summary> ///set Cardctrl return Cardctrl/// </summary> PublicCardctrl Cardctrl {Set { //Gameobject.destroy (cardCtrl.transform.parent.gameObject);Cardctrl =value; } Get{returnCardctrl;} } /// <summary> ///the weight of the return card/// </summary> Public intGetcardweight {Get{returnweight;} } /// <summary> ///the ownership of the card/// </summary> PublicCardtype.charactertype Attribution {Set{belongto =value;} Get{returnbelongto;} }}
Then, after the static class is prepared, there is a static method inside the static class that adds the extension method to the class we want to extend:
SayHello is our way of extending, the parameter is the class that we want to extend, with this callout.
public static class nnn
{
public static void SayHello (this card)
{
Debug.Log ("This is an extension method");
C # Extension methods