使用接口成员实现接口

jst*_*ark 3 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?
}
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*rth 6

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

public class Bar : IBar 
{ 
    public IFoo Answer { get; set; }   
} 
Run Code Online (Sandbox Code Playgroud)

注意:IFoo而不是Foo.

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

想一想:

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