c#在多个表单之间共享一个类

本文关键字:一个 之间 表单 共享 | 更新日期: 2023-09-27 18:26:27

我一直在四处寻找,发现了一些与我相同问题的答案,但我确实尝试了代码,但它在我的情况下不起作用。我试着做同样的事情。我的目标是使许多不同的形式能够使用一个类来做一些事情。

以下是我班的简化版:

public class test
{
somedll g = new somedll();
somedll h = new somedll();
public void Stop(int module)
    {
        string command = "STOP";
        if (module == 1)
        {
            this.WriteCommand(1, command);
        }
        else if (module == 2)
        {
            this.WriteCommand(2, command);
        }
    }
private void WriteCommand(int module, string command)
    {
        try
        {
            if (module == 1)
            {
                g.write(command + ''r');
            }
            else if (module == 2)
            {
                h.write(command + ''r');
            }
        }
        catch (Exception)
        {
            if (module == 1)
            {
                gconnected = false;
            }
            else if (module == 2)
            {
                hconnected = false;
            }
            MessageBox.Show("<Write failed> Please connect.");
        }
    }

由于我的问题是,我无法使用static使我的类能够被所有表单共享,因为static在共享变量/数据方面更有效。

edit*:我实际上不需要static,我只需要让这个类可以从所有其他形式访问,而不需要声明新的实例,我提到static是因为我确实尝试过使用它,但它无法编译。

不创建多个实例的问题是因为我需要集中数据。由于声明多个实例会导致所有表单获得独立的数据。

edit*:我的目标是在不从每个表单创建新实例的情况下,将上面显示的这个类与其他表单一起使用。例如,在每个form1、form2、form3和form4中,我都需要访问"stop",然后stop将依次调用"writecommand"以最终发出命令。因此,由于在方法中有一些调用,static无法使用(在我的知识领域中,只有c#

有办法解决这个问题吗?感谢

c#在多个表单之间共享一个类

您可以将类的单个实例传递给多个表单(通过构造函数或属性)。但是,您可能需要通过使用锁定来确保类线程的安全。

非静态类的静态实例是表单访问单个实例的另一种方式,但这通常不是最好的方法,因为它将类和表单更紧密地耦合在一起。

编辑

要扩展,非静态类的静态实例可能如下所示:

public class test
{
    private static test singleInstance = new test();
    public static test SingleInstance { get { return singleInstance; } }
    somedll g = new somedll();
    somedll h = new somedll();
    public void Stop(int module)
    {
        // ...
    }
    private void WriteCommand(int module, string command)
    {
        // ...
    }
}

或者它可能在另一个班级。

另一种(可能更好的)方法是在创建表单的代码中创建一个新实例,并将其传递给表单的构造函数,可以将其编辑为这样的内容:

class MyForm : Form
{
    private readonly test testInstance;
    public MyForm(test testInstance)
    {
        this.testInstance = testInstance;
    }
}

据我所知,您希望创建一个类的实例,从一个表单更改它的值,并希望该实例的更改值可以从其他表单访问。你说你不能用静态,但我认为你可以。你有没有尝试过使用静态类,比如:

static class YourClass
{
    private static string _yourVar= "";
    public static string YourVar
    {
        get { return _yourVar; }
        set { _yourVar = value; }
    }
}

并将其更改为:

YourClass.YourVar = "your value"

我强烈建议阅读这篇文章。