【问题标题】:How to correctly override and enhance property如何正确覆盖和增强属性
【发布时间】:2016-09-27 09:05:03
【问题描述】:

代码说明的不仅仅是文字,所以看看这个:

public abstract class ViewObject: INotifyPropertyChanged {
  public virtual string Id {
    get {
      return this.GetType().Name;
    }
  }
}

public class Object : ViewObject {
  private string id = string.Empty;
  public override string Id {
    get {
      return this.id;
    }
    set {
      this.id = value;
    }
  }
}

在抽象类中实现基本实现的所需行为的正确方法是什么(是的,它应该有一个基本实现,而不是其他东西)?

我只能想到使用new 键而不是override 来简单地隐藏基本实现,但是这样对吗?

【问题讨论】:

    标签: c# .net oop


    【解决方案1】:

    您已经在使用继承。当方法名称和参数相同时,覆盖方法很有用。 在这里你可以使用方法重载。 对于方法重载名称相同但参数不同。您也可以在继承中使用。 我希望这是有用的

    【讨论】:

      【解决方案2】:

      如果您使用new 关键字并且有人将您的派生对象强制转换为基类,则将调用基类实现而不是派生类。为避免这种情况,需要override

      但这目前是不可能的,因为您的基类不支持 setter。所以坚持override 并在基类中实现一个set 方法,该方法简单地抛出一个NotSupportedExecption

      public abstract class ViewObject
      {
          public virtual string Id
          {
              get { return this.GetType().Name; }
              set { throw new NotSupportedException(); }
          }
      }
      
      public class Object : ViewObject
      {
          private string id = string.Empty;
          public override string Id
          {
              get { return this.id; }
              set { this.id = value; }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-04
        • 2022-07-21
        • 2017-04-06
        • 2011-05-29
        • 2011-11-06
        • 2015-01-08
        • 2013-12-16
        相关资源
        最近更新 更多