C#将旧接口函数传递给新接口

时间:2012-11-10 05:28:33

标签: c# oop design-patterns

以前曾问过类似的问题,但我找不到这样的答案。

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...*/}
}

如何获得包含我可以传递的Property1Property2的界面“I2”?

4 个答案:

答案 0 :(得分: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接口。

答案 1 :(得分:2)

您似乎正在尝试做一些界面不适合的事情。接口只是一个契约,当一个类实现该契约时,它承诺它将以某种方式实现它,但接口本身不关心因为它不关心本身有实施细节。如果要将行为传递给子项,则需要子类化。

但是,如果你真的想要从父接口创建一个“承载函数”的接口,那么这肯定是支持并且很容易实现。您需要做的就是创建一个继承父级的子接口。

示例:

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

而且,接口支持多重继承......玩得开心!

答案 2 :(得分:1)

显式实施怎么样?

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...*/}
}

答案 3 :(得分:0)

您无法从课程中获取界面。为什么你不能单独使用C2?