实现具有自己的接口(interface)成员的接口(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?
}
我已经使用显式接口(interface)实现解决了我的问题,但我想知道是否有更好的方法?
最佳答案
你需要使用泛型才能做你想做的事。
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; }
}
这将允许您提供一个接口(interface),其内容类似于“要实现此接口(interface),您必须具有一个具有实现
IFoo
类型的公共(public) getter/setter 的属性。”如果没有泛型,您只是说该类具有类型为 IFoo
的属性,而不是任何实现 IFoo
的属性。关于c# - 使用接口(interface)成员实现接口(interface),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12391592/