3

之前有人问过类似的问题,但我找不到这样的答案。

C#

public interface I1 { //sealed interface, cannot change
  string Property1 {get; set;}
  void OnEvent();
}
public class C1 : I1 {//sealed class, cannot change
  public string Property1 {get; set;}
  public virtual void OnEvent() {/*update property1...*/}
}
public class C2 : C1 {//my class inherits C1. Now I want I2 for my class C2
  public string Property2 {get; set;}
  public override void OnEvent() {base.OnEvent(); /*populate property2...*/}
}

如何获得包含Property1并且Property2可以传递的接口“I2”?

4

4 回答 4

2

It seems like you are trying to do something that an interface isn't meant for. An interface is simply a contract and, when a class implements that contract, it is promising that it will fulfill it in some way or another, but the interface itself doesn't care since it doesn't concern itself with implementation details. If you want to pass behavior on to children, you need to subclass.

However, if you really are trying to create an interface that "carries functions" over from a parent interface, that is definitely supported and easily accomplished. All you need to do is create a child interface to inherit your parent.

Example:

interface IParentInterface
{
   int FirstProperty {get;set;}
   void OnChange();
}

interface IChildInterface: IParentInterface
{
   string SecondProperty {get;set;}
}

class InterfaceInheritanceGoodness: IChildInterface
{
   public int FirstProperty { get; set; }

   public string SecondProperty { get; set; }

   public void OnChange()
   {
       throw new NotImplementedException();
   }
}

And, interfaces support multiple inheritance... Have fun!

于 2012-11-10T05:52:40.573 回答
2
public interface I2 { 
    string Property1 {get; set;}
    string Property2 {get; set;}
}

public class C2 : C1, I2 {
    public string Property2 {get; set;}
    public override void OnEvent() {base.OnEvent(); /*populate property2...*/}
}

由于C2已经从基类中实现了 Property1,它将用于隐式实现I2接口。

于 2012-11-10T05:51:34.153 回答
1

What about explicit implementation?

public class C2 : C1, I2 
{
    string I2.Property1 
    {
        get { return base.Property1; } 
        set { base.Property1 = value; }
    }
    public string Property2 {get; set;}
    public override void OnEvent() {base.OnEvent(); /*populate property2...*/}
}
于 2012-11-10T05:52:30.657 回答
0

您无法从类中获取接口。为什么不能单独使用 C2?

于 2012-11-10T05:42:09.743 回答