C#自定义扩展方法 及 EventHandler<TEventArgs> 委托

有自定义官方示例链接:

如何实现和调用自定义扩展方法 - C# | Microsoft Learn

1.静态类

2.静态方法

3.第一参数固定为this + 要修改的类型,后面才是自定的参数

AI给出的一个示例:没有自定义参数 、有自定义参数的

复制代码
using System;
using System.Collections.Generic;
using CustomExtensions;

namespace ExtensionMethodExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个整数列表
            List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

            // 调用扩展方法 Sum,计算列表中所有数字的总和
            int total = numbers.Sum();

            // 输出结果
            Console.WriteLine($"Sum of all numbers in the list is: {total}");
        }
    }
}

namespace CustomExtensions
{
    // 定义一个静态类来存放扩展方法
    public static class ListExtensions
    {
        // 定义一个扩展方法 Sum,用于计算 List<int> 中所有数字的总和
        public static int Sum(this List<int> list)
        {
            int total = 0;
            foreach (int number in list)
            {
                total += number;
            }
            return total;
        }
    }
}

using System;
using System.Collections.Generic;
using CustomExtensions;

namespace ExtensionMethodExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个整数列表
            List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            // 指定阈值
            int threshold = 5;

            // 调用扩展方法 Sum,计算大于阈值的数字的总和
            int total = numbers.Sum(threshold);

            // 输出结果
            Console.WriteLine($"Sum of numbers greater than {threshold} is: {total}");
        }
    }
}

namespace CustomExtensions
{
    // 定义一个静态类来存放扩展方法
    public static class ListExtensions
    {
        // 定义一个扩展方法 Sum,用于计算 List<int> 中大于指定阈值的数字的总和
        public static int Sum(this List<int> list, int threshold)
        {
            int total = 0;
            foreach (int number in list)
            {
                if (number > threshold)
                {
                    total += number;
                }
            }
            return total;
        }
    }
}

EventHandler<TEventArgs> 委托 (System) | Microsoft Learn

相关推荐
lph197221 分钟前
csharp设计方法
c#
黑听人22 分钟前
【力扣 简单 C】141. 环形链表
c语言·开发语言·数据结构·算法·leetcode
JNU freshman1 小时前
windows 开发
windows·c#
Blossom.1181 小时前
基于深度学习的智能图像分类系统:从零开始构建
开发语言·人工智能·python·深度学习·神经网络·机器学习·分类
缘友一世1 小时前
java设计模式[2]之创建型模式
java·开发语言·设计模式
cyc&阿灿2 小时前
Java中extends与implements深度解析:继承与接口实现的本质区别
java·开发语言
liujing102329294 小时前
Day13_C语言基础&项目实战
c语言·开发语言
周振超的4 小时前
c++编译第三方项目报错# pragma warning( disable: 4273)
开发语言·c++
JH30735 小时前
Java Stream API 在企业开发中的实战心得:高效、优雅的数据处理
java·开发语言·oracle
呆呆的小草8 小时前
Cesium距离测量、角度测量、面积测量
开发语言·前端·javascript