C# 使用接口成员实现接口

C# 使用接口成员实现接口,c#,interface,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 Fo

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

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

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

您需要使用与接口中完全相同的类型:

public class Bar : IBar 
{ 
    public IFoo Answer { get; set; }   
} 
注意:
IFoo
而不是
Foo

原因是接口定义了一个契约,契约说它必须是
IFoo

想想看:


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

IBar有一个IFoo字段,而不是一个Foo字段,请执行以下操作:

public class Bar : IBar
{
    // other stuff

    public IFoo Answer { get; set; }
}

Foo可以扩展IFoo类型,但接口不会公开这种类型。 接口定义了一个合同,您需要遵守该合同的条款。 所以正确的方法是使用
public-IFoo-Answer{get;set;}
就像其他人所说的那样。

您需要使用泛型来实现您想要的功能

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
{
字符串{get;set;}
字符串二{get;set;}
}
公共接口IBar
T:IFoo在哪里
{
//其他东西。。。
T回答{get;set;}
}
公共类Foo:IFoo
{
公共字符串{get;set;}
公共字符串二{get;set;}
}
公共类酒吧:IBar
{
//其他东西
公共Foo应答{get;set;}
}

这将允许您提供一个接口,该接口类似于“要实现此接口,您必须具有一个具有实现
IFoo
类型的公共getter/setter的属性”,而没有泛型,您只是说该类具有一个类型为
IFoo
的属性,除了实现任何
IFoo

之外,您能用显式接口实现来显示代码吗?您好,请解释一下为什么@jstark代码不起作用,而IBar实现需要IFoo属性,而Foo是IFoo!!!谢谢。@Parsa
IBar
说您需要有一个接受并返回
IFoo
的属性,但并不是说它有一个接受并返回
Foo
的属性。您需要准确地实现接口成员。