使用接口成员实现接口

时间:2012-09-12 15:27:39

标签: c# interface

实现具有自己的接口成员的接口的正确方法是什么? (我说得对吗?)这就是我的意思:

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?
}

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

4 个答案:

答案 0 :(得分:6)

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

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

注意:IFoo代替Foo

原因是界面定义了合同,合同说它必须是IFoo

想一想:

您有FooFoo2类,都是IFoo。根据合同,可以分配两个类的实例。现在,如果您的代码是合法的,那么这会因为您的类只接受Foo而中断。显式接口实现不会以任何方式改变这一事实。

答案 1 :(得分:3)

你需要使用泛型才能做你想做的事。

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; }
}

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

答案 2 :(得分:0)

IBar有一个IFoo字段,而不是Foo字段,而是这样做:

public class Bar : IBar
{
    // other stuff

    public IFoo Answer { get; set; }
}

答案 3 :(得分:0)

Foo可能会扩展IFoo类型,但这不是接口公开的内容。 界面定义合同,您需要遵守该合同的条款。 所以正确的方法是使用 public IFoo Answer{get;set;}和其他人一样说过。