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

相关推荐
黄贵根1 小时前
JavaScript实现教培行业意向登记系统
开发语言·javascript·ecmascript
zzzll11114 小时前
Claude Code离线安装方案揭秘
开发语言·php
wling03015 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
郝学胜-神的一滴5 小时前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
xrandzj6 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
DLYSB_7 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
雨田言炎8 小时前
四、关于Qt项目需要知道的
开发语言·笔记·qt
猿长大人9 小时前
C# | JSON 序列化中的多态接口处理:基于 Attribute 实现精准 $type 控制
c#·json
程序喵大人9 小时前
【C++进阶】STL算法与函数对象 - 02 sort为什么需要随机访问迭代器
开发语言·c++·算法
SomeB1oody9 小时前
【RustyML入门】2.6. 线性判别分析
开发语言·后端·机器学习·rust·教程