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

相关推荐
coding随想10 分钟前
掌控网页的魔法之书:JavaScript DOM的奇幻之旅
开发语言·javascript·ecmascript
爱吃烤鸡翅的酸菜鱼29 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
神仙别闹1 小时前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
向宇it2 小时前
【unity组件介绍】URP Decal Projector贴花投影器,将特定材质(贴花)投影到场景中的其他对象上。
游戏·3d·unity·c#·游戏引擎·材质
古月-一个C++方向的小白7 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发7 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州8 小时前
Python笔记
开发语言·笔记·python