[英]How do I provide a default implementation in a child interface?
If I have an interface IExampleInterface
:如果我有一个接口
IExampleInterface
:
interface IExampleInterface {
int GetValue();
}
Is there a way to provide a default implementation for GetValue()
in a child interface?有没有办法在子接口中为
GetValue()
提供默认实现? Ie: IE:
interface IExampleInterfaceChild : IExampleInterface {
// Compiler warns that we're just name hiding here.
// Attempting to use 'override' keyword results in compiler error.
int GetValue() => 123;
}
After more experimentation, I found the following solution:经过更多的实验,我找到了以下解决方案:
interface IExampleInterfaceChild : IExampleInterface {
int IExampleInterface.GetValue() => 123;
}
Using the name of the interface whose method it is that you're providing an implementation for is the right answer (ie IParentInterface.ParentMethodName() =>...
).使用您为其提供实现的方法的接口的名称是正确的答案(即
IParentInterface.ParentMethodName() =>...
)。
I tested the runtime result using the following code:我使用以下代码测试了运行时结果:
class ExampleClass : IExampleInterfaceChild {
}
class Program {
static void Main() {
IExampleInterface e = new ExampleClass();
Console.WriteLine(e.GetValue()); // Prints '123'
}
}
In C# 8.0+ the interfaces can have a default method:在 C# 8.0+ 中,接口可以有一个默认方法:
https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods
Otherwise if you are using lower version on C# due to using.Net Framework, you may use an abstract class.否则,如果由于使用 .Net Framework 而在 C# 上使用较低版本,则可以使用抽象 class。 but If you want your classes to be able to implement several interfaces, this option may not work for you:
但是如果您希望您的类能够实现多个接口,则此选项可能不适合您:
public abstract class ExampleInterfaceChild : IExampleInterface {
int GetValue() => 123;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.