首页 > 解决方案 > 从基类执行方法时,如何从派生类中获取要使用的变量?

问题描述

我正在尝试使用从基类继承的两个不同的派生类,每个派生类都有一个彼此不同的布尔变量。布尔值已在基类和派生类中分配。但是,当我从派生类访问仅在基类中声明的方法时,布尔值会导致基类的结果。

我已经尝试在每个类中执行一个方法来初始化其声明的变量。没有进行任何更改。

public partial class Form2 : Form
{
    public class BaseC : Form
    {
        public bool reversePlace = false;

        public void computeInput(BaseC cc)
        {
            if (reversePlace)
            {
                //Execute condition
                if (cc.reversePlace)
                {
                    //Execute execution from other derived class
                }
            }
        }
    }


    public class DerivedC1 : BaseC
    {
        public bool reversePlace = true;
    }

    public class DerivedC2 : BaseC
    {
        public bool reversePlace = false;
    }

    DerivedC1 C1 = new DerivedC1();
    DerivedC2 C2 = new DerivedC2();

    public Form2()
    {
        C1.computeInput(C2); //Should execute first condition for being true while ignoring the inner condtion for being false
    }

}

在跳过 C2 的 if 条件时,我应该从 C1 获得一个 if 语句完成一半。C1 的布尔值应该为真,而 C2 的布尔值应该为假。但是,这两个布尔值都被视为错误。

标签: c#basederived-class

解决方案


使其成为虚拟财产。当它是虚拟的并且被覆盖时,即使是在基类中定义的代码也会查看当前实例的最覆盖的属性。

public class BaseC : Form
{
    public virtual bool ReversePlace => false;
    //etc....
}


public class DerivedC1 : BaseC
{
    public override bool ReversePlace => true;
}

public class DerivedC2 : BaseC
{
    public override bool ReversePlace => false;
}

推荐阅读