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

相关推荐
z落落27 分钟前
C# 泛型方法(原理、类型推断、多泛型参数)+泛型效率(普通类型 VS Object装箱 VS 泛型)
开发语言·c#
L_090729 分钟前
【C++】异常
开发语言·c++
世辰辰辰1 小时前
批量修改图片/文本名子
开发语言·python·批量修改文件名
rockey6272 小时前
基于AScript的SQL脚本语言发布啦!
sql·c#·.net·script·expression·动态脚本
z落落3 小时前
C# 四种特殊类:抽象类、密封类、静态类、部分类
开发语言·c#
VidDown4 小时前
Webhook 调试器:让第三方回调“原形毕露”
java·开发语言·javascript·编辑器·postman
装不满的克莱因瓶4 小时前
基于 OpenResty 扩展开发实现动态服务注册与发现能力
java·开发语言·架构·openresty
weixin_523185325 小时前
Java基础知识总结(四):引用数据类型与参数传递机制
java·开发语言·python
Nayxxu5 小时前
Claude API 生产稳定性设计:超时、降级、备用模型和告警怎么做
开发语言·php
王cb5 小时前
WinRT Server and Client c#
开发语言·c#