第八章 生产线上的一个有用的功能

第八章 生产线上的一个有用的功能

扩展方法

扩展方法为现有类型添加新的方法(从面向对象的角度来说,是为现有对象添加新的行为)而无需修改原有类型,这是一种无侵入而且非常安全的方式。扩展方法是静态的,它的使用和其他实例方法几乎没有什么区别。常见的扩展方法有Linq扩展、有IEnumerable扩展等。

为什么要有扩展方法呢?这里,我们可以顾名思义地想一下,扩展扩展,那么肯定是涉及到可扩展性。

扩展方法的三个要素是:静态类、静态方法以及this关键字。

public class StudentScore
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Chinese { get; set; }
    public int English { get; set; }
    public int Math { get; set; }

    public int Sum()
    {
        return Chinese + English + Math;
    }

    public int Sum(double proportion)
    {
        return Convert.ToInt32(Chinese * proportion + English * proportion + Math);
    }
}

给StudentScore添加一个扩展方法

public static class StudentScoreExtension
{
    public static string FormatOutPut(this StudentScore score)
    {
        return string.Format("ID:{0},Name:{1},Chinese:{2}", score.Id, score.Name, score.Chinese);
    }
}
  1. 静态类:扩展方法必须定义在一个静态类中。
  2. 静态方法:扩展方法本身必须是静态的。
  3. this 参数:扩展方法的第一个参数前加上 this 关键字,指定要扩展的类型。

全部代码如下:

namespace ConsoleApp6
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<StudentScore> students = new List<StudentScore>()
            {
                new StudentScore(){Id = 101, Name = "张三", Chinese = 80, English = 97, Math = 88},
                new StudentScore(){Id = 101, Name = "李四", Chinese = 96, English = 92, Math = 93},
                new StudentScore(){Id = 101, Name = "王五", Chinese = 60, English = 93, Math = 70},
            };

            foreach (var s in students)
                Console.WriteLine(s.FormatOutPut());
        }
    }

    public class StudentScore
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Chinese { get; set; }
        public int English { get; set; }
        public int Math { get; set; }

        public int Sum()
        {
            return Chinese + English + Math;
        }

        public int Sum(double proportion)
        {
            return Convert.ToInt32(Chinese * proportion + English * proportion + Math);
        }
    }

    public static class StudentScoreExtension
    {
        public static string FormatOutPut(this StudentScore score)
        {
            return string.Format("ID:{0},Name:{1},Chinese:{2}", score.Id, score.Name, score.Chinese);
        }
    }
}

Console.WriteLine(s.FormatOutPut())中的s.FormatOutPut(),明明StudentScore类中没有FormatOutPut()方法,仍然可以调用。因为使用扩展方法给StudentScore类添加了一个方法(功能)。

posted @ 2025-05-26 18:17  冲浪的奶糖  阅读(9)  评论(0)    收藏  举报