在C#中,子类跳过父类方法直接实现接口方法可以通过显式接口实现或重新实现接口来实现。
1、显式接口实现
当子类需要跳过父类的接口实现时,可以使用显式接口实现语法:
public interface IFoo
{
void Do();
}
public class Parent : IFoo
{
public void Do()
{
Console.WriteLine("Parent implementation");
}
}
public class Child : Parent, IFoo
{
// 显式实现接口,跳过父类方法
void IFoo.Do()
{
Console.WriteLine("Child's explicit implementation");
}
}
2、重新实现接口
子类也可以重新实现父类已实现的接口:
public class Parent : IFoo
{
// 父类正常实现接口
public void Do()
{
Console.WriteLine("Parent implementation");
}
}
public class Child : Parent, IFoo
{
// 重新实现接口,覆盖父类的实现
public new void Do()
{
Console.WriteLine("Child's reimplementation");
}
}
3、关键区别与注意事项
显式接口实现的特点:
- 方法没有访问修饰符
- 只能通过接口类型调用,不能通过类实例直接调用
- 避免多个接口方法签名冲突
重新实现接口的特点:
- 使用new关键字隐藏父类方法
- 可以通过类实例直接调用
- 适用于需要完全替换父类实现的情况
5、调用方式示例:
Child child = new Child();
// 显式实现:child.Do(); // 编译错误
// 显式实现正确调用方式:
IFoo foo = child;
foo.Do(); // 输出 "Child's explicit implementation"
// 重新实现:
child.Do(); // 输出 "Child's reimplementation"
选择哪种方式取决于具体需求:如果需要完全隐藏父类实现且只在接口上下文中使用,选择显式接口实现;如果需要在类实例层面也使用新的实现,选择重新实现接口。
960

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



