C# 类扩展方法

扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
扩展方法要点:
一、定义的扩展类必须为静态类如上
public static class ExtendNpc。

二、定义的扩展方法必须为静态方法如上
public static void SetIDName(this Npc npc, int id, string name)。

三、扩展方法的第一个参数必须使用 this 指定该方法用于那种类型如上SetIDName(this Npc npc, int id, string name) 该方法只能 Npc 类的对象调用。

四、如果 Npc 类本身已经定义了一个 SetIDName 方法,则扩展方法中的 SetIDName无效,即如果扩展方法与该类型中定义的方法具有相同的签名,则扩展方法永远不会被调用。

建议:
只建议你无法更改源代码来扩充你需要的方法时实现扩展方法,并谨慎地实现。只要有可能,最好重构原始类,或从现有类派生子类来达到这一目的。

  // 定义 Npc 类
    public class Npc
    {
        //定义字段变量
        private int npcId;
        private string name;

        public Npc() { }

        //定义字段变量对应的属性
        public int NpcID
        {
            get { return npcId; }
            set { npcId = value; }
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }

    // 扩展 Npc 类
    public static class ExtendNpc
    {
        // 给 Npc 类扩展一个方法
        // SetIDName(this Npc npc, int id, string name)
        public static void SetIDName(this Npc npc, int id, string name)
        {
            npc.NpcID = id;
            npc.Name = name;
        }
    }

调用:

class Program
    {
        static void Main(string[] args)
        {
            // 实例一个 Npc 对象
            Npc npc = new Npc();

            // Npc 类对象就可以直接调用扩展方法了
            npc.SetIDName(1000, "HeHe");

            int npcId = npc.NpcID;
            string name = npc.Name;

            Console.WriteLine("npcId    :" + npcId);
            Console.WriteLine("name     :" + name);

            Console.ReadLine();
        }
    }

 

 

 

原文地址:https://www.cnblogs.com/wfy680/p/14361906.html