【问题标题】:Overriding Properties with Attributes用属性覆盖属性
【发布时间】:2013-07-19 10:54:49
【问题描述】:

假设我有 3 个班级(父母、儿子和女儿)。我希望 Son 和 Daughter 使用 Parent 的 Name getter 方法,但我想分别为每个子类应用不同的属性。

public class Parent {

private string name;

public string Name { 
  get { return this.name; }
  set { this.name = value != null ? value.trim() : null; }
}

}

和儿子...

public class Son : Parent { 
  [SonAttribute]
  public string Name { // keep parent behavior }
  }
}

女儿的Name getter 方法相同,但具有[Daughter] 属性。

我可以这样做吗?

【问题讨论】:

  • @TGH - 感谢您的回答(看起来它已被删除)。我选择 p.s.w.g 是因为我不完全理解 new 关键字与方法有关。

标签: c# inheritance properties attributes


【解决方案1】:

假设Name 虚拟在Parent

public class Parent 
{
    public virtual string Name 
    { 
        get { return this.name; }
        set { this.name = value != null ? value.trim() : null; }
    }
}

你总是可以这样做:

public class Son : Parent 
{
    [SonAttribute]
    public override string Name 
    { 
        get { return base.Name; }
        set { base.Name = value; }
    }
}

如果Name 属性不是虚拟的,您将创建一个新属性隐藏基类型上的属性,这可能不是您想要的。详情请见Knowing When to Use Override and New Keywords (C# Programming Guide)

【讨论】:

  • Son 和 Daughter 类的 name 字段是属于父亲还是孩子?
  • @Kevin 私有字段将属于Parent 类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 2016-07-20
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多