从基类对象问题访问派生类

时间:2010-08-03 01:24:21

标签: c# wpf user-controls derived-class

我有一种奇怪的情况......

我在WPF中有一个用户控件又有一些其他用户控件附加到它上面,然后我有一个庞大的C#代码文件,需要访问用户控件UI元素和方法的大算法,这个漏洞过程有效使用Timer从用户控件向C#代码文件算法发送数据,它需要返回并更新控件中的UI元素,并访问它的方法......

现在问题是我不想把这个巨大的算法放在我的控件的codebehind文件中,而是想从该代码文件中访问控件的UI元素和声明的方法......

我到目前为止尝试的是从我使用的用户控件实际派生代码文件的类,这工作正常但花花公子但是访问派生类我需要创建它的新对象和我显示的UI没有得到更新,因为它还创建了一个新的基类对象,我相信......

所以我有类似的东西:

public partial class usrctrlSimulator : UserControl
{
    public usrctrlSimulator()
    {
        this.InitializeComponent();          
    }

    public void StartSimulator()
    {
        Algorithm = new csAlgorithm();

        Algorithm.InitializeSimulator();

        timer1.Start();
    }
}

public class csAlgorithm : usrctrlSimulator
{
    public csAlgorithm()
    {
    }

    public void InitializeSimulator()
    {
         txtblkSimulatorStatus.Text = "Started"; // this element would be from the user control
    }
}

所以我的问题是:如何在不实例化其新对象的情况下调用派生类,因为这将导致创建新的用户控件对象并且不会更新显示的UI ...或者如果我不知道导出算法类,我有什么可能访问用户控件元素和方法?

1 个答案:

答案 0 :(得分:0)

如果您想坚持使用控件的一个实例并仍然可以访问派生类中的功能,那么您需要使用派生类作为控件。因此,不是usrctrlSimulator的实例,而是在任何地方都使用csAlgorithm。

但是,我不确定这种设计是否是您方案中的最佳方法。该算法实际上不是用户控件,因此可能从usrctrlSimulator派生并不是理想的选择。例如:UserControl有一个名为ApplyTemplate()的方法。在csAlgorithm中这是什么意思?您还可以从不同的角度来看待它:在csAlgorithm使用UserControl的任何地方使用UserControl.AddLogicalChild(csAlgorithm)是否合理,例如何时调用usrctrlSimulator

另一种选择是将算法实例化为usrctrlSimulator(复合)中的成员变量。在这种情况下,您仍然可以在public partial class usrctrlSimulator : UserControl { public usrctrlSimulator() { this.InitializeComponent(); } public void StartSimulator() { _algorithm= new csAlgorithm(); _algorithm.InitializeSimulator(); timer1.Start(); } private csAlgorithm _algorithm; } public class csAlgorithm // not a UserControl anymore { public csAlgorithm() { } public void InitializeSimulator() { txtblkSimulatorStatus.Text = "Started"; // this element would be from the user control } } 中使用它,但是您可以清楚地分离两个概念:一方面是UserControl,另一方面是算法的实现。此外,您可以更改其中任何一个,而对另一个的影响有限。

在这种情况下,您的代码将如下所示:

{{1}}