简体   繁体   中英

How do I provide a default implementation in a child interface?

If I have an interface IExampleInterface :

interface IExampleInterface {
    int GetValue();
}

Is there a way to provide a default implementation for GetValue() in a child interface? 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() =>... ).

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:

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. 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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM