接口成员不能有定义
Interface members cannot have a definition
为什么我无法添加此接口的默认实现?
我有 C# 8 / .NET Core 3.0(如 Main 中所示)
但出于某种原因它大喊:
'ITest.Test()': interface members cannot have a definition
interface ITest
{
// Interface members cannot have a definition
void Test()
{
Console.WriteLine("Interface");
}
}
public class Test : ITest
{
void ITest.Test()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
// this works properly
var arr = "test".ToCharArray();
Console.WriteLine(arr[1..2]);
Console.WriteLine(arr[..2]);
Console.WriteLine(arr[..^1]);
Console.WriteLine(arr[^1..]);
}
}
默认接口方法功能是 not available yet, even in the C# 8.0 preview(微软代表在回复 "Rand.Random" 评论者询问此功能未在预览中时确认)。
如果你想提供一个实现,我会推荐使用继承和虚拟方法。
public class TestBase
{
public virtual void TestMethod()
{
Console.WriteLine("TestBase");
}
}
public class Test : TestBase
{
public override void TestMethod()
{
throw new NotImplementedException();
}
}
public class Program
{
public static void Main(string[] args)
{
var testBase = new TestBase();
testBase.TestMethod(); // Prints "TestBase"
var test = new Test();
test.TestMethod(); // Throws NotImplementedException
}
}
因为这个功能还不可用。根据 C# 8.0 测试版 dymanoid's link, this feature is in the prototype stage. It's not mentioned in the blog post。
为什么我无法添加此接口的默认实现?
我有 C# 8 / .NET Core 3.0(如 Main 中所示)
但出于某种原因它大喊:
'ITest.Test()': interface members cannot have a definition
interface ITest
{
// Interface members cannot have a definition
void Test()
{
Console.WriteLine("Interface");
}
}
public class Test : ITest
{
void ITest.Test()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
// this works properly
var arr = "test".ToCharArray();
Console.WriteLine(arr[1..2]);
Console.WriteLine(arr[..2]);
Console.WriteLine(arr[..^1]);
Console.WriteLine(arr[^1..]);
}
}
默认接口方法功能是 not available yet, even in the C# 8.0 preview(微软代表在回复 "Rand.Random" 评论者询问此功能未在预览中时确认)。
如果你想提供一个实现,我会推荐使用继承和虚拟方法。
public class TestBase
{
public virtual void TestMethod()
{
Console.WriteLine("TestBase");
}
}
public class Test : TestBase
{
public override void TestMethod()
{
throw new NotImplementedException();
}
}
public class Program
{
public static void Main(string[] args)
{
var testBase = new TestBase();
testBase.TestMethod(); // Prints "TestBase"
var test = new Test();
test.TestMethod(); // Throws NotImplementedException
}
}
因为这个功能还不可用。根据 C# 8.0 测试版 dymanoid's link, this feature is in the prototype stage. It's not mentioned in the blog post。