使用接口成员实现接口

3

如何正确实现一个带有自己接口成员的接口?(我的表述是否正确?)这是我的意思:

public Interface IFoo
{
    string Forty { get; set; }
    string Two { get; set; }
}

public Interface IBar
{
    // other stuff...

    IFoo Answer { get; set; }
}

public class Foo : IFoo
{
    public string Forty { get; set; }
    public string Two { get; set; }
}

public class Bar : IBar
{
    // other stuff

    public Foo Answer { get; set; } //why doesnt' this work?
}

我使用显式接口实现解决了我的问题,但我想知道是否有更好的方式?

1
请问您能否展示一下显式接口实现的代码? - Daniel Hilgarth
4个回答

6

您需要使用与界面中完全相同的类型:

public class Bar : IBar 
{ 
    public IFoo Answer { get; set; }   
} 

注意:Foo应改为IFoo
原因是接口定义了一种契约,这个契约规定它必须是IFoo
想一想:
你有类FooFoo2,它们都实现了IFoo。 根据契约,可以分配两个类的实例。 现在,如果您的代码合法,这会在某种程度上导致问题,因为您的类只接受Foo。 显式接口实现不改变这个事实。

4

您需要使用泛型来实现您的需求。

public interface IFoo
{
    string Forty { get; set; }
    string Two { get; set; }
}

public interface IBar<T>
    where T : IFoo
{
    // other stuff...

    T Answer { get; set; }
}

public class Foo : IFoo
{
    public string Forty { get; set; }
    public string Two { get; set; }
}

public class Bar : IBar<Foo>
{
    // other stuff

    public Foo Answer { get; set; }
}

这将允许您提供一个界面,比如说,“要实现这个接口,你必须有一个公共的 getter/setter 类型的属性,该属性实现了 IFoo 接口。” 没有泛型,您只是说这个类有一个类型为 IFoo 的属性,而不是任何实现了 IFoo 接口的类型。


你好,请问能否解释一下为什么@jstark的代码无法工作,而IBar的实现需要一个IFoo属性和Foo是IFoo!谢谢。 - Parsa
1
@Parsa IBar说您需要拥有一个接受和返回IFoo的属性,而不是接受和返回Foo的属性。您需要精确地实现接口成员。 - Servy

0

IBar 有一个 IFoo 字段,而不是 Foo 字段,请改成这样:

public class Bar : IBar
{
    // other stuff

    public IFoo Answer { get; set; }
}

0

Foo 可以扩展类型 IFoo,但这不是接口所公开的内容。 接口定义了一个合同,你需要遵守该合同的条款。 因此,正确的方式是像其他人建议的那样使用 public IFoo Answer{get;set;}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接