繁体   English   中英

如何从另一个类访问表单的方法以确保它是相同的Form实例-C#

[英]How to access a method of a form from another class ensuring it is the same Form instance - C#

更新以更加清晰。

我有一个主窗体Form1和一个附加类AslLib Form1包含一种更新其包含的dataGridView控件的方法。 AslLib的方法称为此方法。

我的问题是,使AslLib调用Form1方法的唯一方法是在AslLib的调用方法中创建Form1的实例,如下所示:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void updateDataGUI(int row, string url, string status, long time)
    {
        Console.WriteLine(status);
        foreach (DataGridViewRow dgvr in dataGridView1.Rows) dgvr.Cells[0].Value = status;
    }

}



static class AslLib
{
    public static async void makeRequest(string url, int row )
    {
        string result;
        Stopwatch sw = new Stopwatch(); sw.Start();

        try
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = new HttpResponseMessage();
                response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    result = ((int)response.StatusCode).ToString();
                }
                else
                {
                    result = ((int)response.StatusCode).ToString();
                }
            }
        }
        catch (HttpRequestException hre)
        {
            result = "Server unreachable";
        }

        sw.Stop();
        long time = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));


        _form.updateDataGUI(row, url, result, time);

    }
}

我尝试过在构造函数和方法中传递参数,但是由于( 我认为makeRequest方法是静态的,因此编译器给出了错误:

AsyncURLChecker.AslLib._form: cannot declare instance members in a static class              AsyncURLChecker
Static classes cannot have instance constructors                AsyncURLChecker

上面的结果是Console.WriteLine(status); Form1的方法的一部分正确地输出status ,但dataGridView不会更改。

我的信念是,因为我正在创建Form1的新实例,所以我不再引用包含我的dataGridView的原始Form1 ,而是一个全新的副本,因此它不会更改。

谁能告诉我如何从另一个类操纵原始Form1的dataGridView 我的首选方法是调用Form1方法来更新dataGridView而不是尽可能地直接从AslLib访问dataGridGiew

您应该传递对现有表单的引用,而不是创建新表单:

// on Form1
Class1 c1 = new Class1();
c1.DoSomething(this);

// Class1
public void DoSomething(Form1 form)
{
    form.updateDataGUI(row, url, result, time);
}

将表单传递给类构造函数

private Form1 _form;
public Class1(Form1 form)
{
    _form = form;
}

现在,您可以从班级内部访问表单。

您需要拥有MainForm的原始创建实例。 这是一种访问方式:

Application.OpenForms.OfType<MainForm>().First().updateDataGUI(row, url, result, time);

Application.OpenForms包含当前正在运行的应用程序的所有打开的窗体。)

但是最好以可以将MainForm对象的引用传递给类的方式重新设计类结构。 另一种选择是将实例保存在MainForm本身的静态属性中(如果您确定任何时候都只有一个实例)。

我想你可以用这个。

MainForm f = (MainForm)this.Owner;
f.updateDataGUI(row, url, result, time);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM