编译时,扩展方法的优先级总是比类型本身中定义的实例方法低。
如果某个类型具有一个名为 GoHome() 的方法,又有一个名为GoHome的扩展方法,则编译器总是绑定到该实例方法。
public class Student
{
public void Run()
{
Console.WriteLine("run");
this.GoHome(); //内部调用拓展方法需要使用this关键字,否则会报错
}
}
public class GoodStudent : Student
{
// public void GoHome()
// {
// Console.WriteLine("g go home");
// }
public void Run()
{
this.GoHome();
}
}
public static class StudentRegister
{
public static void GoHome(this Student student)
{
Console.WriteLine("go home");
}
}
class Program
{
static void Main()
{
// Student stu = new Student();
// stu.Run();
//
// stu.GoHome();
GoodStudent gstu = new GoodStudent();
//gstu.GoHome();
gstu.Run();
}
}