c# - 从另一个类 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()
但Text
inbutton
没有改变,我不知道为什么。
解决方案
您应该提供对现有表单的引用以对其进行修改,而不是创建新表单。为此,将依赖项注入以下构造函数: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
- 方法本身。
推荐阅读
- google-calendar-api - 谷歌日历:限制 API 访问单个日历?
- firebase - 使用本机反应设置 Firebase
- php - Symfony 4记住我没有用户名就不能工作
- c# - 从文件反序列化加密对象
- xcode - 为什么在终端中找不到我的 Xcode 项目文件夹?
- javascript - 如何检查对可观察对象的活动订阅以避免 Angular 中的内存泄漏
- fluid - 如何将参数传递给 link.typolink 以进行标记?
- authentication - 如何对 Google Cloud Endpoint 进行经过身份验证的调用?
- elixir - 如何在 Absinthe GraphQL 请求中接受 JSON
- python - 在 Python 中为数据找到合适的多项式拟合