问题
C# 8.0 has a new feature that lets you add a default implementation to a method on an interface. Either I'm doing something wrong or this feature doesn't work as advertised. (I'm guessing it's the former.)
I created a new .NET Core 3.1 console app with the following code:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var xxx = new MyClass { MyInt = 5 };
Console.WriteLine(xxx.GetItNow());
}
}
public interface ITest
{
int MyInt { get; set; }
int GetItNow() => MyInt * 2;
}
public class MyClass : ITest
{
public int MyInt { get; set; }
}
}
The Console.WriteLine(xxx.GetItNow()));
statement doesn't compile because
Myclass does not contain a definition for 'GetItNow()'...
So, the compiler is happy with the fact that MyClass
doesn't explicitly reference GetItNow()
(it doesn't complain the MyClass
doesn't implement the interface). But it doesn't see the default interface member as a public method of the class that implements the interface.
Am I missing something, or is something broken?
回答1:
Well, interface default method belongs to the interface not to a class which implements it; so you have two possibilities:
Cast:
Console.WriteLine(((ITest)xxx).GetItNow()));
Declaration change (preferable; MyClass
is implementation detail, often it's a dependency; ITest
- contract is the only thing which matter):
ITest xxx = new MyClass { MyInt = 5 };
// xxx is ITest, so xxx.GetItNow() is legal now
Console.WriteLine(xxx.GetItNow());
来源:https://stackoverflow.com/questions/61717649/cant-get-c-sharp-default-interface-method-to-compile