gpt4 book ai didi

c# - 接口(interface)引用另一个接口(interface)但类引用 C# 中的另一个类

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:58 24 4
gpt4 key购买 nike

我有一个很简单的问题,但我以前没有遇到过这个问题。

看看这段代码:

interface IFoo
{
IBar MyBar { get; }
}

interface IBar
{
String Test { get; }
}

class Foo : IFoo
{
public Bar MyBar { get; set; }
}

class Bar : IBar
{
public String Test { get; set; }
}

问题是 Foo 没有实现 IFoo,因为它返回 Bar 而不是 IBar。但我没有看到问题,因为 Bar 正在实现 IBar。我错过了什么吗?

我希望我的应用程序使用类 Foo 但将 IFoo 暴露给解决方案的其他部分。

这是一种绕过它的方法,但它似乎是一个丑陋的解决方案:

class Foo : IFoo
{
public Bar MyBar { get; set; }
IBar IFoo.MyBar {
get { return this.MyBar; }
}
}

这是要走的路还是更好的路?

最佳答案

你可以这样做:

interface IFoo<out B> where B:IBar
{
B MyBar { get; }
}

interface IBar
{
String Test { get; }
}

class Foo : IFoo<Bar>
{
public Bar MyBar { get; set; }
}

class Bar : IBar
{
public String Test { get; set; }
}

这仅在 B 处于输出位置的情况下有效(原因很明显,如果你考虑得够久的话)。

关于c# - 接口(interface)引用另一个接口(interface)但类引用 C# 中的另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16357224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com