【问题标题】:How to Override a Property without marked like Partial, abstract or extern in the Base Property?如何覆盖基础属性中没有标记为 Partial、abstract 或 extern 的属性?
【发布时间】:2015-12-21 11:44:22
【问题描述】:

我在远程服务器中有一个名为HasChar 的属性,类型为Bool。我需要在我的 Derived 类中重新定义它并进行一些修改。但是基本属性没有标记为Partialabstractextern。但我需要重新定义,我该如何实现?在派生类中,我需要访问派生类中基类的HasChar属性,如果值为False,则必须将BlogText设为String.Empty

注意:基类在远程服务器中,我无法更改它或 启动更改。基类属性未标记为 Partialabstractextern。不要创建任何额外的属性来实现这一点。请提供与 Override 或类似的解决方案。

我的基类

public class BlogBase
{
    private string _blogText = string.Empty;
    public string BlogText 
    { 
        get { return _blogText; }; 
        set 
        {
            _blogText = value;
            HasChar = _blogText.Length >0 ? true : false;
        } 
    }

    public bool HasChar { get; set; }

}

我的派生类:粗略代码

public class BlogChild : BlogBase
{
    private bool _hasChar = false;
    public bool HasChar 
    { 
        get { return _hasChar; }; 
        set 
        {
            _hasChar = value;
            if(!_hasChar)
                BlogText = string.Empty;
        } 
    }

}

【问题讨论】:

  • 尝试用“new”关键字标记属性,或者制作一些包装器并使用它
  • @Alex 我无法更改基类,请查看注释。
  • @CodeCaster - 我向您展示了示例代码。我无法解释整个项目。我需要如上所述的要求。如果你理解要求,那就给你答案,否则不要。

标签: c# class inheritance properties overriding


【解决方案1】:

使用 new 关键字隐藏原始属性。

public new bool HasChar
{
    private bool _hasChar;
    get { return _hasChar; }
    set
    {
         // do other stuff
         _hasChar = value;
    }
}

【讨论】:

  • 请查看要求。然后请发布答案。
  • 我错过了哪个要求?
  • 您检查派生类功能以及注释。
  • 编辑了答案。您可能不需要访问基类属性,因此应该可以工作。
猜你喜欢
  • 1970-01-01
  • 2015-01-12
  • 2011-03-18
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
相关资源
最近更新 更多