我在 Visual Studio 2019 中有一个 .Net 6.0 应用程序。 我正在尝试让默认接口(interface)实现正常工作。 出于某种原因,它似乎无法识别默认实现 在类定义中。
这是一个示例代码片段:
public interface IFooBar
{
protected bool BoolProperty { get; set; }
protected Guid StringProperty { get; set; }
protected void SampleMethod1(string param)
{
}
protected void SampleMethod2()
{
}
}
public class FooBase
{
}
public class Foo : FooBase, IFooBar
{
protected bool IFooBar.BoolProperty { get; set; }
protected Guid IFooBar.StringProperty { get; set; }
protected SomeMethod()
{
SampleMethod1("Test String");
}
}
这是我的 Visual Studio 2019 项目文件中的一个片段:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>preview</LangVersion>
</PropertyGroup>
这是我看到的错误消息。
Error CS0103 The name 'SampleMethod1' does not exist in the current context
我有两个问题:
为什么编译器要求我在我的具体类中定义接口(interface)属性: protected bool IFooBar.BoolProperty { 得到;放; } protected Guid IFooBar.StringProperty { get;放;
为什么我的具体类无法识别默认方法实现?
最佳答案
它turns out protected 默认接口(interface)方法成员必须由实现类显式实现,但只能从派生接口(interface)访问。
例如:
public interface IBase
{
protected string StringProperty { get; set; }
protected void BaseMethod(string param) => Console.WriteLine($"IBase.BaseMethod: {param}");
}
public interface IDerived : IBase
{
public void DerivedMethod()
{
// SampleMethod1, SampleMethod2 and StringProperty are accessible.
BaseMethod(StringProperty);
}
}
public class Foo : IDerived
{
// Protected DIM properties must be explicitly implemented.
// They can be initialized, interestingly, but are otherwise inaccessible to Foo.
string IBase.StringProperty { get; set; } = "StringProperty";
public void Test()
{
// Public DIM members are available via cast
((IDerived)this).DerivedMethod();
}
// Protected DIM members can be overridden.
// There doesn't seem to be a way to access the base method in the override.
void IBase.BaseMethod(string param) => Console.WriteLine($"Foo.BaseMethod: {param}");
}
SharpLab .
关于c# - 为什么我的 C# 默认接口(interface)实现在具体类定义中没有被识别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69761049/