c# - 为什么我的 C# 默认接口(interface)实现在具体类定义中没有被识别?

标签 c# .net-core default-interface-member

我在 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

我有两个问题:

  1. 为什么编译器要求我在我的具体类中定义接口(interface)属性: protected bool IFooBar.BoolProperty { 得到;放; } protected Guid IFooBar.StringProperty { get;放;

  2. 为什么我的具体类无法识别默认方法实现?

最佳答案

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/

相关文章:

c# - 我必须做什么才能访问我自己的公共(public)方法?

c# - 我们什么时候应该在 C# 中使用默认接口(interface)方法?

c# - 自动属性的默认接口(interface)方法和默认值

c# - ASP.Net web api 后操作参数总是为空

c# - 工厂类知道的太多了

c# - 如何在 Roslyn 动态编译代码中引用另一个 DLL

c# - EF Core,通过从字符串进行 int 转换在 SQL 服务器上执行

c# - 析构函数和终结器的区别?

c# - 通过 json 传递 datetime 时 API 对象为 null