【问题标题】:Why are default implementations of interfaces in a implementing struct not visible? [duplicate]为什么实现结构中接口的默认实现不可见? [复制]
【发布时间】:2020-12-23 10:26:19
【问题描述】:

当我在接口中有一个方法的默认实现,然后有一个带有这个接口的结构时,该方法不作为结构的成员存在。为什么?或者我理解错了什么? 示例:

    using System;

namespace test
{
    public interface ITestInterface
    {
        public bool TestMe() => true;
        public bool TestMe2();
    }

    public struct teststruct : ITestInterface
    {
        public int somevalue;
        // implementing this will create a NEW method but not implement the interface
        // public bool TestMe() => true; 

        public bool TestMe2() => false;
    }

    class a
    {
        public static void Main()
        {
            var ts = new teststruct();
            ts.TestMe(); // this doesnt exist
        }
    }
}

在此示例中,结构中不存在方法 TestMe(),但必须实现 TestMe2()(如预期的那样)。

【问题讨论】:

  • 结构和接口是一个特殊情况,有很多注意事项,请在此处阅读:docs.microsoft.com/en-us/archive/blogs/abhinaba/…
  • 这并不能真正解释手头的问题。
  • 您需要手动将其转换为ITestInterface,因为它是隐藏的,并且无论是类还是结构都没有区别。高度怀疑这个说法是否正确:this will create a NEW method but not implement the interfacedotnetfiddle.net/ilx9V8
  • implementing this will create a NEW method but not implement the interface @RandRandom 是正确的 - 这个说法是不正确的。 dotnetfiddle.net/dRlZ3Q

标签: c# struct interface


【解决方案1】:

您必须看到一个接口,例如必须具有继承它的对象的合同。

您的测试结构没有te方法TestMe(),包含实现的是接口。所以它不存在于你的结构范围内。

如果你想访问接口的方法,你应该这样做:

(ts as ITestInterface).TestMe();

或:

((ITestInterface)ts).TestMe();

【讨论】:

  • C# 8 允许在接口上实现默认实现(很多博客文章解释了原因)。当使用类而不是结构时,TestMe() 将作为成员存在(因为默认实现)
  • @Hefaistos68 - 你关于类和结构的陈述是错误的
  • 该死,我的错。也不存在于一个类中。
  • @mjwills 可能是对的,我会编辑答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 2014-10-01
  • 2015-01-15
  • 2013-09-20
  • 2010-11-18
  • 1970-01-01
  • 2010-11-06
相关资源
最近更新 更多