C#高级语言特性深度解析
1. 扩展方法
扩展方法允许我们在不修改现有类型代码的情况下,为其添加新的方法。但需要注意的是,扩展方法并非传统的继承方式,在扩展方法的作用域内,无法直接访问被扩展类型的成员。
例如,尝试为 Car 类型创建一个 SlowDown() 扩展方法:
public static class CarExtensions
{
public static int SlowDown(this Car c)
{
// Error! This method is not deriving from Car!
return --Speed;
}
}
上述代码会产生编译错误,因为 SlowDown() 是 CarExtensions 类的静态成员,在这个上下文中 Speed 并不存在。正确的做法是使用 this 限定的参数来访问被扩展类型的所有公共成员:
public static class CarExtensions
{
public static int SlowDown(this Car c)
{
// OK!
return --c.Speed;
}
}
此时,可
超级会员免费看
订阅专栏 解锁全文
2204

被折叠的 条评论
为什么被折叠?



