有一个非常简单的方法来处理这个:
- 将默认方法声明为静态。不用担心,您仍然可以在继承自它的类中覆盖它。
- 调用类的静态方法时使用相同类型的语法调用默认方法,只需用接口名替换类名即可。
此代码适用于 C#8 或更高版本,如果针对 .NET Framework 构建,它将不起作用。我使用 C#9 在 Windows 10 上运行它,在 .NET 6 上运行,预览版 5。
例子:
public interface IGreeter
{
private static int DisplayCount = 0;
public static void SayHello(string name)
{
DisplayCount++;
Console.WriteLine($"Hello {name}! This method has been called {DisplayCount} times.");
}
}
public class HappyGreeter : IGreeter
{
public void SayHello(string name)
{
// what can I put here to call the default method?
IGreeter.SayHello(name);
Console.WriteLine("I hope you're doing great!!");
}
}
public class CS8NewFeatures
{
// This class holds the code for the new C# 8 features.
//
public void RunTests()
{
TestGreeting();
}
private void TestGreeting()
{
// Tests if a default method may be called after a class has implemented it.
//
var hg = new HappyGreeter();
hg.SayHello("Pippy");
hg.SayHello("Bob");
hg.SayHello("Becky");
}
}
示例输出:
Hello Pippy! This method has been called 1 times.
I hope you're doing great!!
Hello Bob! This method has been called 2 times.
I hope you're doing great!!
Hello Becky! This method has been called 3 times.
I hope you're doing great!!
如本例所示,现在接口中也允许使用静态字段。
如果由于某种原因您不能使用静态接口方法,那么您始终可以依赖以下技术:
- 将默认方法实现代码放入单独的静态方法中。
- 从默认实现方法调用此静态方法。
- 在接口方法的类实现的顶部调用此静态方法。
例子:
public class DefaultMethods
{
// This class is used to show that a static method may be called by a default interface method.
//
public static void SayHello(string name) => Console.WriteLine($"Hello {name}!");
}
public interface IGreeter
{
void SayHello(string name) => DefaultMethods.SayHello(name);
}
public class HappyGreeter : IGreeter
{
public void SayHello(string name)
{
// what can I put here to call the default method?
DefaultMethods.SayHello(name);
Console.WriteLine("I hope you're doing great!!");
}
}
public class CS8NewFeatures
{
// This class holds the code for the new C# 8 features.
//
public void RunTests()
{
TestGreeting();
}
private void TestGreeting()
{
// Tests if a default method may be called after a class has implemented it.
//
var hg = new HappyGreeter();
hg.SayHello("Bob");
}
}
样本输出:
Hello Bob!
I hope you're doing great!!