【发布时间】: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