扩展方法
扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
方法所在的类必须是静态的。
方法也必须是静态的。
扩展方法是通过实例方法语法进行调用的。
方法的第一个参数必须是你要扩展的那个类型,并且该参数使用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();