【问题标题】:Visual Studio calling method placed in Form by otside class由otside类放置在Form中的Visual Studio调用方法
【发布时间】:2017-01-01 19:16:21
【问题描述】:

在我开始之前,我想说我知道这个论坛上有类似的帖子。不幸的是,在我的情况下,他们没有工作。我确定这是我的错。我希望你能帮助我。

这是我的情况:

我写了 windows 窗体,它像终端一样工作。我有向这个终端添加文本的功能。我想从自定义类中调用这个函数。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace terminal
{
    public partial class Form1 : Form
    {
        Test testClass = new Test() ;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            terminal(textBox1.Text);
        }

        public void terminal(string text)
        {
            richTextBox1.AppendText(text);
            richTextBox1.AppendText("\n");
        }
    }

    public class Test
    {
        Form1.terminal("sample tekst");
    }
}

而且这东西行不通。当我开始调试时,我可以看到内存在增加,但没有出现任何形式。我的问题是我无法访问函数 addToLog();来自类 LoadSomeFiles。 Visual Studio 为整行加下划线

Form1.terminal("sample tekst");

红色。如果我写了这种奇怪的东西,我很抱歉。我是新手。

源文件:Program

感谢您的帮助!

【问题讨论】:

  • 这甚至不能编译,更不用说演示问题了。
  • 整个程序有 600 多行。我不能把他放在这里。它不会是可读的。我发布了我的程序的简化想法。
  • 什么时候打电话?
  • 只需创建一个minimal reproducible example。并查看checklist 以解决有助于回答您问题的其他要点。
  • 如果您在表单/类之间共享功能,我建议创建一个包含这些静态功能的新静态类,以便您可以在任何需要的地方使用它。

标签: c# winforms visual-studio class namespaces


【解决方案1】:

只需创建您需要的对象的实例。在这种情况下,Form1 对象。 然后你就可以像以前一样访问它了。

这就是我的意思:

Form1 form1 = new Form1();
form1.terminal("sample text");

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 2015-08-27
    • 2016-11-13
    相关资源
    最近更新 更多