[英]Is it possible in C# to have interface with fields of another interface but in the implementation use a class that implements an interface?
The following is an example implementation.下面是一个示例实现。
But when I do it I get the following error 'Foo' does not implement interface member 'IBar.MyBar'.但是当我这样做时,我得到以下错误'Foo'没有实现接口成员'IBar.MyBar'。
public interface IBar
{
public int Id { get; set; }
}
public class Bar : IBar
{
public int Id { get; set; }
}
public interface IFoo
{
public IBar MyBar { get; }
}
public class Foo : IFoo
{
public Bar MyBar { get; }
}
Well, the error is pretty clear: the interface IFoo
indicates a member called a MyBar
of type IBar
, not Bar
.好吧,错误很明显:接口IFoo
指示一个名为MyBar
的成员,类型为IBar
,而不是Bar
。 This contract ensures that you allways know what you can expect from an API.该合同确保您始终了解您可以从 API 获得什么。 So the following will allways return some kind of IBar
:因此,以下内容总是会返回某种IBar
:
IFoo foo = GetMyFoo();
IBar bar = foo.MyBar;
The implementation of your Bar
-class is an internal detail, clients shouldn´t care for.你的Bar
类的实现是一个内部细节,客户不应该关心。 So you can easily exchange that implementation without clients to re-compile.因此,您可以轻松地交换该实现,而无需客户端重新编译。
There´sa proposal for C#9 to make return-types co-variant, though.不过,有一个建议 C#9使返回类型协变。
So, after replicating the code, I think that you need to change the Foo class implementation.所以,复制代码后,我认为你需要更改 Foo class 实现。
As for now you have this:至于现在你有这个:
public class Foo : IFoo
{
public Bar MyBar { get; }
}
And I think you meant to put it this way, which will work as you intend to:而且我认为您的意思是这样说,这将按您的意图工作:
public class Foo : IFoo
{
public IBar MyBar { get; }
}
Note that in the IFoo Interface you implement MyBar as IBar and not as Bar, thus the error.请注意,在 IFoo 接口中,您将 MyBar 实现为 IBar 而不是 Bar,因此会出现错误。 If I'm missing something I am sorry, but I think that this is the problem.如果我遗漏了什么,我很抱歉,但我认为这就是问题所在。 Glad if I could help you: :)很高兴我能帮助你::)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.