【问题标题】:How to get access to form's controls from class C#如何从 C# 类中访问表单的控件
【发布时间】:2015-06-26 17:11:18
【问题描述】:

当我尝试从另一个类访问表单控件时遇到问题。我的程序挂在无限循环中。我知道为什么,但我不知道如何正确地写这个。
这是 Form1.cs(到我的表单)

public Form1()
    {
        InitializeComponent();
        Load config = new Load();

        string[] data = config.readConfig("config.ini");
        if (data.Length == 4) { //client
            Client run = new Client();
            run.startClient(data[1], Convert.ToInt32(data[2]));
        }
        else if (data.Length == 3) //server
        {
            Server run = new Server();
            run.startServer(Convert.ToInt32(data[1]));

        }
    }


public void addLog(string dataLog){
            richTextBox1.Text += dataLog;
        }

这是 Client.cs 文件:

class Client
{

    public void startClient(string ipAddr, int port)
    {
        Form1 form1 = new Form1();

            TcpClient client = new TcpClient();
            try
            {

                form1.addLog("Connecting...");

                client.Connect(ipAddr, port);
                form1.addLog("Connected to server: " + ipAddr + ":" + port.ToString());

            }
            catch
            {
                MessageBox.Show("We couldn't connect to server");
            }

    }


}

如何在不运行每次新表单的情况下更改文本值。也许有类似 run_once 的东西?

【问题讨论】:

    标签: c# winforms infinite-loop


    【解决方案1】:

    无限循环在这里:

    表格1:

    //Always runs if the config file is a certain length
    Client run = new Client();
    

    客户:

     Form1 form1 = new Form1();
    

    每个构造函数都会创建另一个对象,而后者又会创建第一个对象 ad infintum。

    如果您需要将表单对象发送给客户端不要创建一个新对象!。无论如何它都不起作用,因为您的新表单对象对旧表单对象一无所知。把它传进去:

    public Client(Form1 form)
    {
       //Do whatever with it
    }
    
    //Form class
    Client c = new Client(this);
    

    免责声明:通常有更好的方法可以做到这一点,但随着您对设计模式/架构越来越熟悉,您将了解这些方法。

    【讨论】:

    • 要访问 Client 类中的 Form1 控件,您需要在 Form1 中创建内部属性或将要处理的控件的“Modifiers”属性更改为“内部”。
    • @Graffito 虽然是真的,但很明显他已经可以访问他需要的成员,但他不应该在Client中创建新表单
    猜你喜欢
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多