C#扩展方法

本文介绍了扩展方法的概念,它允许向现有类型添加方法而无需继承或使用装饰器。文章通过示例展示了如何定义扩展方法,包括无参数和带参数的用法,如对象转换为JSON和字符串时间比较。扩展方法的语法规定它们必须定义在静态类的静态方法中,第一个参数前缀为`this`,以指定方法应用于哪个类型。
摘要由CSDN通过智能技术生成

1.扩展方法定义

向现有的类型“添加”方法。例如:String Int Class DataTable等

2.语法规则
  • 扩展方法定义在静态类的静态方法中
  • 第一个参数指定该方法用于哪个类型,并该参数以 this 修饰符为前缀
  • 扩展方法后面只有一个 this 修饰的参数不属于方法参数,此扩展是无参方法
3.无参数
class Program
{
    static void Main(string[] args)
    {
         List<UserInfo> list = new List<UserInfo>
        {
            new UserInfo{ Name="zs",Age=10,Sex="男"},
            new UserInfo{ Name="ls",Age=11,Sex="女"},
            new UserInfo{ Name="ww",Age=12,Sex="男"},
        };
        
        var result = list.Where(it => it.Age > 10).ToList().ToJson();
        Console.ReadLine();
    }
}


public static class Extension
{
    public static string ToJson(this object obj)
    {
        return JsonConvert.SerializeObject(obj);
    }
}
4.一个参数
class Program
{
    static void Main(string[] args)
    {
         string beginTime = “10:30”;
         string endTime = “10:50”;
         bool b = beginTime.CompareTime(endTime);
         Console.ReadLine();
    }
}


public static class Extension
{
   public static bool CompareTime(this string str1, string str2)
    {
        DateTime d1 = Convert.ToDateTime(str1);
        DateTime d2 = Convert.ToDateTime(str2);
        if (DateTime.Compare(d1, d2) > 0)
            return true;  // d1>d2
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DotNeter-Hpf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值