Is it possible to override default interface methods in another interface?
Assume I have the following code:
public class Program
{
public static void Main()
{
IOriginal origOrig = new Original();
IOriginal origInh = new Inherited();
IInherited inherited = new Inherited();
Console.WriteLine($"IOriginal Original: {origOrig.Method()}");
Console.WriteLine($"IOriginal Inherited: {origInh.Method()}");
Console.WriteLine($"IInherited Inherited: {inherited.Method()}");
}
}
public interface IOriginal
{
string Method() => "original";
}
public interface IInherited : IOriginal
{
string Method() => "inherited";
}
public class Inherited : IInherited {}
public class Original : IOriginal {}
The output is
IOriginal Original: original
IOriginal Inherited: original
IInherited Inherited: inherited
However, I would like to override the method in IInherited
interface, so it produces this:
IOriginal Original: original
IOriginal Inherited: inherited
IInherited Inherited: inherited
In the C# 8 specification proposal , it was proposed by doing this:
interface IA
{
void M() { WriteLine("IA.M"); }
}
interface IB : IA
{
override void IA.M() { WriteLine("IB.M"); } // explicitly named
}
interface IC : IA
{
override void M() { WriteLine("IC.M"); } // implicitly named
}
But in the official release, it is not working?
Compilation error: The modifier 'override' is not valid for this item
Is there any way to achieve this?
Using:
interface IB : IA
{
void IA.M() { WriteLine("IB.M"); } // explicitly named
}
I can't find any C# docs saying that this is the correct syntax however!
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.