【问题标题】:C# carry old interface functions to new interfaceC#将旧接口函数携带到新接口
【发布时间】:2012-11-10 05:28:33
【问题描述】:

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

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

【问题讨论】:

  • 另外,在调用类“密封”时应该更加小心。密封修饰符的含义见msdn.microsoft.com/en-us/library/88c54tsw%28v=vs.71%29.aspx。如果您的类是真正密封的,那么您将无法继承它。这同样适用于接口,但更是如此,因为密封修饰符对接口无效。我之所以提到这一点,是因为它会使知识较少的开发人员感到困惑并可能产生误导。

标签: c# oop design-patterns


【解决方案1】:

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

但是,如果您真的想创建一个从父接口“承载功能”的接口,那肯定是受支持且很容易实现的。您需要做的就是创建一个子接口来继承您的父接口。

例子:

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】:
    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 接口。

    【讨论】:

      【解决方案3】:

      显式实现呢?

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

        • 用于测试目的。我们可以构建模拟接口。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-26
        • 2014-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-13
        • 1970-01-01
        相关资源
        最近更新 更多