调用在另一个函数 c# 中具有参数类型的函数
本文关键字:函数 参数 类型 另一个 调用 | 更新日期: 2023-09-27 18:33:03
>我在表单上得到了这个函数:
private void UpdateQuantityDataGridView(object sender, DataGridViewCellEventArgs e)
{
(...codes)
}
我想在另一个函数中调用该函数,假设当我单击"确定"按钮时,下面的函数将运行并执行上面具有参数类型的函数。
private void button5_Click(object sender, EventArgs e) // This is the "OK" button click handler.
{
SubmitButton(sender, e);
}
private void SubmitButton(object sender, EventArgs e) // This is function of "OK" button
{
(...codes)
UpdateQuantityDataGridView("What should i put in here? I tried (sender, e), but it is useless")
}
我知道当我们放置这样的东西时,这个函数会运行: dataGridView1.CellValueChanged += new DataGridViewSystemEventHandler(...);
但是,我不希望这样,因为该函数仅在 DataGridView 中的单元格值已更改时才运行,我想在单击"确定"按钮时访问该功能。但是,我应该在参数值中放入什么?
UpdateQuantityDataGridView()
方法中的逻辑,并将其放入一个名为您想要的任何名称的新public
方法中,然后您可以从类中的任何位置或引用您的类的任何其他代码调用此逻辑,如下所示:
public void DoUpdateQuantityLogic()
{
// Put logic here
}
注意:如果您实际上没有使用 sender
或 e
,那么您可以将上面的方法保留为没有参数,但是如果您确实使用 e
,例如,您需要为 DoUpdateQuantityLogic()
方法提供一个参数来说明您正在使用的e
对象的属性是什么。
现在,您可以从其他方法调用DoUpdateQuantityLogic()
,如下所示:
private void button5_Click(object sender, EventArgs e) // This is the "OK" button click handler.
{
DoUpdateQuantityLogic();
}
private void SubmitButton(object sender, EventArgs e) // This is function of "OK" button
{
DoUpdateQuantityLogic();
}
这允许您重用逻辑,并且如果您选择对此逻辑进行单元测试,还可以将功能隔离到使单元测试更容易的方法中。
如果确定使用现有的基于事件的方法基础结构,则可以为事件处理程序的sender
和e
参数传递null
,如下所示:
UpdateQuantityDataGridView(null, null);
如果您的方法实际上UpdateQuantityDataGridView()
使用参数sender
和e
?如果不是,则只需为两者传递空值。
UpdateQuantityDataGridView(null, null);
如果您正在使用它们:
var e = new DataGridViewCellEventArgs();
// assign any properties
UpdateQuantityDataGridView(dataGridView1, e);
您可以使用 sender,但不能使用 e,因为 UpdateQuantityDataGridView 需要 e 的类型为 DataGridViewCellEventArgs。
根据 UpdateQuantityDataGridView 处理程序想要对 e 参数执行的操作,当您从 SubmitButton 调用它时,您可以只传递 null。否则,您必须新建一个 DataGridViewCellEventArgs,并使用您自己的处理程序需要/期望的适当值填充它。