从 Derived 更改 Base class 字段值

Change Base class field value from Derived

我有一个问题,是否可以从派生 class 更改基础 class 的字段值。在我的例子中,我有两个 classes base class with windows form RichTextBox,我想使用 derived class 清除 RichTextBox

初始化RichTextBox:

        this.rtfCode.Location = new System.Drawing.Point(45, 26);
        this.rtfCode.Name = "rtfCode";
        this.rtfCode.ShowSelectionMargin = true;
        this.rtfCode.Size = new System.Drawing.Size(100, 96);
        this.rtfCode.TabIndex = 1;
        this.rtfCode.Text = "some text";

基础class:

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Console.WriteLine(this.rtfCode.Text);
        DerivedClass f = new DerivedClass();
        Console.WriteLine(f.rtfCode.Text);
    }
}

我的派生 class

    class DerivedClass:Program
{
    public DerivedClass()
    {
        base.rtfCode.Clear();
    }
}

当我执行程序并按 RichTextBox 中的 button 时,我仍然看到文本。

Program a = new Program(); // a is an instance of Program
Console.WriteLine(a.rtfCode.Text);
DerivedClass f = new DerivedClass();// f is an instance of DerivedClass, which has nothing to do with a
Console.WriteLine(a.rtfCode.Text);

af 不是同一个实例。 DerivedClass... 派生自 Program 的事实对此没有任何改变。

您必须将最后一行替换为

Console.WriteLine(f.rtfCode.Text);