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;
}
}
作者:DotNeter-Hpf
出处:https://www.cnblogs.com/DotNeter-Hpf/p/16620562.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
客官,点个推荐再走可好
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?