0

我的思想不知何故陷入了“错误循环”。我不想再用无休止的反复试验浪费时间,所以我最好在这里问:

我有一个 Windows 窗体(.NET,C++),如下所示。这里的简化版只有一个RichTextBox,一个静态成员函数和一个非静态成员函数。从非静态函数“ nonstaticFunc() ”将文本附加到 RichTextBox 可以按预期工作。

但是我怎样才能从静态成员函数“ staticFunc() ”中做到这一点?我尝试了这个论坛中提出的几种关于如何从静态函数调用非静态函数的方法,但不知何故我无法弄清楚如何做到这一点。

public ref class Form1 : public System::Windows::Forms::Form
    {

    public:
        Form1()
        {
            InitializeComponent();
        }

    protected:
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }

    protected: 

    private:
        System::ComponentModel::Container ^components;

    private: System::Windows::Forms::RichTextBox^  myTextBox;




    System::VoidInitializeComponent( System::Void )
    {
        System::ComponentModel::ComponentResourceManager^  resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid));
        this->myTextBox = (gcnew System::Windows::Forms::RichTextBox());
    }

    public: System::Void nonstaticFunc( System::Void )
    {
        this->myTextBox->AppendText( L"Append this...\n" );
    }

    public: static System::Void staticFunc( System::Void )
    {
        // How do I AppendText here??
        // Not working: this->myTextBox->AppendText( L"Append this...\n" );
    }
}

感谢每一点帮助!非常赞赏!

4

1 回答 1

1

您需要确定您对哪个文本框感兴趣。如果有两个可见的表单怎么办?你没有足够的上下文。

现在您可以保留一个静态成员来跟踪“一个真实的表单” - 或者您可以将文本框或表单作为参数......但基本上您需要以某种方式拥有该上下文。

你为什么要这样做staticFunc呢?为什么调用者不能调用相应表单上的方法?一旦你理解了问题——为什么它不起作用——你应该能够考虑最合适的改变。我们无法真正告诉您,因为我们没有足够的信息。

于 2011-09-23T11:13:50.413 回答