从Derived更改基类字段值

时间:2016-06-24 14:04:57

标签: c# class reflection base-class inherited

我有一个问题是否可以从派生类更改基类的字段值。在我的例子中,我有两个类基类与窗体RichTextBox,我想使用派生类来清除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";

基类:

    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);
    }
}

My Derived class

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

当我执行程序并按下button中的RichTextBox时,我仍会看到文字。

1 个答案:

答案 0 :(得分:1)

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);