扩展方法

扩展方法是一种静态方法,可以在不修改类型的情况下为类型添加新功能。调用时它表现得像实例方法,其实质是静态类中的静态方法。扩展方法要求方法的第一个参数带有this修饰符,表明要扩展的类型。文中通过案例展示了如何为自定义类和C#内置的DateTime类创建扩展方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

扩展方法

扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
方法所在的类必须是静态的。
方法也必须是静态的。
扩展方法是通过实例方法语法进行调用的。
方法的第一个参数必须是你要扩展的那个类型,并且该参数使用this修饰符作为前缀。
扩展方法最终还是会被编译器编译成:静态类.静态方法。
案例1:针对自己创建的类,创建扩展方法。

//创建一个Student类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 扩展方法
{
    public class Student
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

//创建一个类,这个类中写Student类的扩展方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 扩展方法
{
    public static class StudentEX
    {
        public static int GetAge(this Student st)
        {
            return 1;
        }
    }
}

//Main主程序入口
Student st = new 扩展方法.Student();
//StudentEX.GetAge(st);
Console.WriteLine(st.GetAge());
Console.ReadLine();

案例2:针对C#中存在的DateTime这个类创建新的扩展方法

//创建一个DataHelper静态类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 扩展方法
{
    public static class DataHelper
    {
        public static string DateToString(this DateTime dt,int i)
        {
            if (i==0)
            {
                return dt.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                return dt.ToString("yyyy-MM-dd");   
            }
        }
    }
}

//Main主程序入口
DateTime now = DateTime.Now;
string time = now.ToString("yyyy-MM-dd HH:mm:ss");
//DataHelper.DateToString(now, 1);
string time2 = now.DateToString(0);
string time3 = now.DateToString(1);
Console.WriteLine(time);
Console.WriteLine(time2);
Console.WriteLine(time3);
Console.ReadLine();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值