Net Core教程

c#扩展方法

本文主要是介绍c#扩展方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

学生类:

 /// <summary>
    /// 学生实体
    /// </summary>
    public class Student
    {
        public int Id { get; set; }
        public int ClassId { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public void Study()
        {
            Console.WriteLine("{0} {1}跟着Richard老师学习.net高级开发", this.Id, this.Name);
        }

        public void StudyHard()
        {
            Console.WriteLine("{0} {1}跟着Richard老师努力学习.net高级开发", this.Id, this.Name);
        }

    }

 

调用:

                  Student student = new Student()
                    {
                        Id = 1,
                        Name = "Mr.zhang",
                        Age = 25,
                        ClassId = 2
                    };
                    student.Study();

 

之后如果在学生类再加一个方法,正常的情况下是直接在学生类中做修改,但是如果为了遵循开闭原则的话可以做一个扩展方法:

    public static class ExtendMethod
    {  /// <summary>
        /// 扩展方法:添加一个第三方静态类,把当前需要扩展的类作为参数添加方法,在第一个参数前加一个this
        /// </summary>
        /// <param name="student"></param>
        public static void StudyPractise(this Student student)
        {
            Console.WriteLine("{0} {1}跟着Richard老师学习基础班!", student.Id, student.Name);
        } 
    }

 

调用:

   student.StudyPractise(); //扩展方法;看起来跟实例方法调用方式一样

 

这篇关于c#扩展方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!