我想为以下示例创建一个类:
class BaseClass
{
protected int a;
}
class DeriveredClass : BaseClass
{
protected int ownA;
public void CopyFrom(BaseClass b)
{
ownA = b.a;
}
}
但由于保护水平,这似乎是不可能的。问题在于" b"是CopyFrom()方法中的外部对象。
我想要使用的确切代码是创建一个Singleton对象,可以将其升级到派生类型的对象:
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
}
答案 0 :(得分:2)
只需将功能委派给基类。您甚至可以在该类中声明虚拟方法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);
…
}
…
}
答案 1 :(得分:0)
如果可能,您可以创建其他受保护的方法&#39;在您的基类中,例如:
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