首页 > 解决方案 > 从另一个类 c# 调用方法

问题描述

在另一个类中调用方法时,我遇到了一个简单的问题。
我在不同的类文件中有很多类似的代码,我认为我可以使用我经常使用的方法创建一个全局类。
但我不知道如何正确地做到这一点。
请检查我下面的代码并告诉我它可能出了什么问题。
另外,请告诉我是否可以做不同的事情?仅包含一个按钮
Form1

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

    public void ChangeTextInButton1(string newText)
    {
        button1.Text = newText;
    }
    private void Button1_Click(object sender, EventArgs e)
    {
        GlobalMethods gm = new GlobalMethods();
        gm.ChangeTextButtonFromOtherClass();
    }
}

public class GlobalMethods
{
    public void ChangeTextButtonFromOtherClass()
    {
        Form1 f1 = new Form1();
        f1.ChangeTextInButton1("NEW BUTTON NAME");
    }
}

}

当我调用这些方法时效果很好,并且string传递给了ChangeTextInButton1()Textinbutton没有改变,我不知道为什么。

标签: c#functionclassobjectmethods

解决方案


您应该提供对现有表单的引用以对其进行修改,而不是创建新表单。为此,将依赖项注入以下构造函数:GlobalMethods

class GlobalMethods
{
    private readonly Form1 form;
    public GlobalMethods(Form1 f) { this.form = f; }
}

现在您可以在您的ChangeTextButtonFromOtherClass-method 中引用该表单:

public void ChangeTextButtonFromOtherClass()
{
    this.form.ChangeTextInButton1("NEW BUTTON NAME");
}

最后,您需要在 click-eventhandler 中提供该引用:

private void Button1_Click(object sender, EventArgs e)
{
    GlobalMethods gm = new GlobalMethods(this);
    gm.ChangeTextButtonFromOtherClass();
}

或者,将引用传递给您的构造函数GloablMethods也可以将其提供给ChangeTextButtonFromOtherClass- 方法本身。


推荐阅读