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

相关推荐
程序猿乐锅17 分钟前
万字详解Single-flight(单飞模式)
java·开发语言·分布式·后端·学习·single-flight
揽星河..2 小时前
【C语言】指针
c语言·开发语言
小小数媒成员2 小时前
UGUI原理(一)
开发语言·游戏·unity·游戏引擎
WarPigs2 小时前
C#把byte[]以十六进制打印,带分割符
c#
速易达网络2 小时前
Three.js 动画入门教学:从场景搭建到流畅动效
开发语言·javascript·ecmascript
福大大架构师每日一题2 小时前
excelize v2.11.1发布:Go 1.26.0起步,16项安全修复与嵌入对象能力全面升级
开发语言·安全·golang
Sarvartha2 小时前
集合概述 & Collection 接口
开发语言
lhbweilai3 小时前
QT项目(串口助手)
开发语言·qt
eggwyw3 小时前
C++相交链表和反转链表详解
开发语言·c++
Wang's Blog3 小时前
Java 项目实战:交友项目 - 保存访客记录
java·开发语言·交友