【问题标题】:How to make an external object's field accessible in derivered class如何在派生类中使外部对象的字段可访问
【发布时间】:2018-02-11 07:37:10
【问题描述】:

我想为以下示例创建一个类:

class BaseClass
{
    protected int a;
}

class DeriveredClass : BaseClass
{
    protected int ownA;

    public void CopyFrom(BaseClass b)
    {
        ownA = b.a;
    }
}

但由于保护级别,这似乎是不可能的。问题是“b”是 CopyFrom() 方法中的一个外部对象。

我想使用它的确切代码是创建一个单例对象,并有可能将其升级为派生类型的对象:

class MyLogicBase
{
    private static MyLogicBase s_Instance = new MyLogicBase();

    protected MyLogicBase() { }

    public static MyLogicBase Instance
    { get { return s_Instance; } }

    public static Upgrade(MyLogicBase newInstance)
    {
        newInstance.UpgradeInstance(s_Instance);
        s_Instance = newInstance;
    }

    protected virtual void UpgradeInstance(MyLogicBase previousInstance)
    { // To override }

    protected List<string> m_Database = new List<string>();
}

class MyExtendedLogic : MyLogicBase
{
    public override void UpgradeInstance(MyLogicBase newInstance)
    {
        m_Database = newInstance.m_Database;
    }

    // Extended logic here
}

【问题讨论】:

    标签: c# field external protected


    【解决方案1】:

    只需将功能委托给基类。您甚至在该类中声明了虚拟方法 UpgradeInstance

    class MyLogicBase
    {
        …
    
        public virtual void UpgradeInstance(MyLogicBase newInstance)
        { 
            m_Database = from.m_Database;
        }
    
        protected List<string> m_Database = new List<string>();
    }
    
    class MyExtendedLogic : MyLogicBase
    {
        public override void UpgradeInstance(MyLogicBase newInstance)
        {
            base.UpgradeInstance(newInstance);
            …
        }
    
        …    
    }
    

    【讨论】:

    • 您好!感谢您的快速回复。偶然我写了一个代码示例,它没有显示我想要解决的问题。我很抱歉我的错误。更正了它。问题是我希望派生类使用基类对象设置自己,而基类对象的文件仍然对其他人隐藏。
    • @KamilKowalewski 解决方案还是一样的。 UpgradeInstance 虚拟方法是复制 m_Database 字段的正确位置。如果出于任何原因,您不希望在基类UpgradeInstance 中出现这样的常见行为,请为此目的声明另一个方法。
    • 这使它比我想象的要复杂一些。不同的派生类可以以不同的方式使用不同的基类字段。但这解决了我目前的需求。谢谢!
    【解决方案2】:

    如果可能,您可以在基类中创建其他“受保护的方法”,例如:

    class MyLogicBase {
        …
        public virtual void UpgradeInstance(MyLogicBase newInstance)
        {
             //to override
        }
        protected CopyDatabase(MyLogicBase newInstance) {
             m_Database = newInstance.m_Database;
        }
    
        protected List<string> m_Database = new List<string>(); }
    
    class MyExtendedLogic : MyLogicBase
    {
        public override void UpgradeInstance(MyLogicBase newInstance)
        {
            base.CopyDatabase(newInstance);
            …
        }
        …    
    }
    

    或者,您可以尝试使用反射访问受保护的字段,可能是 Accessing a class protected field without modifying original class

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-28
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 2023-03-05
      • 2014-12-05
      • 1970-01-01
      相关资源
      最近更新 更多