Loading

C#扩展方法

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;
    }
}
posted @ 2022-08-24 16:24  DotNeter-Hpf  阅读(122)  评论(0编辑  收藏  举报