从另一个类/命名空间访问形式的标签 [英] Access form label from another class/namespace

查看:168
本文介绍了从另一个类/命名空间访问形式的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这已被要求数以千计的时间,但仍然有大量的研究后,我无法找到一个解决方案,我对这个职位真的很抱歉。

I know this has been asked thousands of time but still after a lot of research I can't find a solution and I am really sorry about this post.

我想从一个类访问我的标签在另一个命名空间。
这是一个代码示例,以更好地了解我所试图做的:

I want to access my Label from a class in another namespace. This is a sample of code to understand better what I am trying to do:

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



//class in another namespace
class Servers
    {
        public void _SetlabelText()
        {
           Main.label1.Text = "New Text";
        }
    }



我怎么做的正确方法?

How am I supposed to do it the proper way?

推荐答案

一个选项是存储在像这样的构造函数形式的引用:

One option is to store a reference to the form in the constructor like this:

public class Servers
{
    private Form _frmMain;
    public Servers(Form frmMain)
    {
        _frmMain = frmMain;
    }
    public void SetlabelText()
    {
        _frmMain.label1.Text = "New Text";
    }
}

和使用这样的:

public partial class Main : Form
{
    public Main()
    {
        InitializeComponent();
        var servers = new Servers(this);
        servers.SetlabelText();
    }
}



然而,它通常建议回返回到窗体类,并设置它在那里,像这样的:

However, it's typically advised to return back to the Form class and set it there, like this:

public partial class Main : Form
{
    public Main()
    {
        InitializeComponent();
        label1.Text = Servers.GetTextForLabel();
    }
}
public class Servers
{
    public static string GetTextForLabel()
    {
       return "New Text"; //(I assume this will be much more complex)
    }
}

这篇关于从另一个类/命名空间访问形式的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆