C#-this关键字的功能之扩展方法

shanzm-2019-02-03 00:35

1. 简介

我们的方法都是与声明他的类的相关联(我们现在写的各个方法都是在类中定义,所以我们调用方法都是用该方法所属类的实体对象调用)。

在C#3.0中的扩展方法的特征,允许声明的方法不是声明该方法的类相关联。



2. 简单实例

下面我们定义了一个Person类,这个类有三个字段,和相应的三个属性
同时有一个方法 IntroductGender()。

 public class Person
    {
        public Person(string name, int age, string gender)
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
        }


        string _name;
        public string Name
        {
            set;
            get;
        }


        private int _age;
        public int Age
        {
            get ;
            set ;
        }

        string _gender;
        public string Gender
        {
            get;
            set;
        }

        //介绍自己姓名和性别
        public void IntroductGender()
        {
            Console.WriteLine($"我是{this.Name},我是一个{this.Gender}生");
        }
    }

现在我们可能会遇到一个问题,我们觉得这个类中的方法不够,我们希望这个类中还有一个方法介绍自己姓名和年龄IntroductAge()。

这时候其实有多种方式

  • 我们可以直接在原有的Person类中进行修改,添加方法IntroductAge()

  • 如果这个类是第三方类库中的类,我们无法修改这个类的定义,但是只要这个类不是密封(sealed)的,我们就可以用这个类派生一个子类,继承遵循着只增不减,我们就可以在子类中添加这个IntroductAge()。

但是很多时候我们无法修改这个Person()类,比如说这个类是第三方类库中的密封类。这时候就可以想到扩张方法

见下面代码实例:

public sealed class Person
    {
        public Person(string name, int age, string gender)
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
        }


        string _name;
        public string Name
        {
            set;
            get;
        }


        private int _age;
        public int Age
        {
            get ;
            set ;
        }

        string _gender;
        public string Gender
        {
            get;
            set;
        }

        //介绍自己姓名和性别
        public void IntroductGender()
        {
            Console.WriteLine($"我是{this.Name},我是一个{this.Gender}生");
        }
    }

//定义一个类这个类是静态类,其中有一个静态方法IntroductAge(),这个方法就是我们想要关联到Person类的方法
//注意定义扩展方法的参数是"this Person p "
 public  static  extendPerson
    {
        public static void IntroductAge(this Person p )
        {
            Console.WriteLine($"我是{p.Name},我的年龄是{p.Age}") 
            
        }          
    }

  

 class Program
    {
        static void Main(string[] args) 
        {
            Person p = new Person("小明",24,"男");

            p.IntroductGender();
         
            //注意这里就是直接使用Person对象p,直接调用IntroductAge(),虽然IntroductAge()并非声明在Person类中

            p.IntroductAge();

            Console.ReadKey();
        }
    }

代码运行结果:

我是小明,我是一个男生
我是小明,我的年龄是24


3. 细节说明

  1. 声明扩展方法的类必须是静态类。
  2. 扩展方法本身必须声明为static
  3. 扩展方法必须包含关键字this 作为他的第一个参数类型,并在后面跟着他所要扩展的类的名称


原文地址:https://www.cnblogs.com/shanzhiming/p/10349512.html