如何在C#中应用多个.Tag属性?

2024-02-17

当我想存储/传递值时,我总是使用 .Tag 属性。例如,当我存储值时:

Form prosesEdit = new FormProsesChemicalRawWbEdit();
                        prosesEdit.Tag = (int)this.proses_chemicalDataGridView.Rows[e.RowIndex].Cells[1].Value;
                        prosesEdit.ShowDialog();

然后,我会将值传递到我的编辑表单中,如下所示:

proses_chemical_id = (int) this.Tag;
            this.proses_chemicalTableAdapter.FillByChemId(this.mcd_softwareDataSet.proses_chemical, proses_chemical_id);
            this.proses_chemical_listTableAdapter.FillByChemId(this.mcd_softwareDataSet.proses_chemical_list, proses_chemical_id);

但最近,我应该存储并传递两个不同的值。比方说(int)this.proses_chemicalDataGridView1.Rows[e.RowIndex].Cells[1].Value; and (int)this.proses_chemicalDataGridView2.Rows[e.RowIndex].Cells[1].Value;我到底该怎么做? 谢谢


到目前为止给出的两个答案都有效,但我想详细说明一下答案并提供替代方案。假设您像这样创建自己的类:

public class YourClass
{
    public int ProsesChemicalId1 { get; set; }
    public int ProsesChemicalId2 { get; set; }
}

然后,您可以将类的实例分配给 Tag 属性,如下所示:

YourClass yourClass = new YourClass();
yourClass.ProsesChemicalId1 = this.proses_chemicalDataGridView1.Rows[e.RowIndex].Cells[1].Value;
yourClass.ProsesChemicalId2 = this.proses_chemicalDataGridView2.Rows[e.RowIndex].Cells[1].Value;

Form prosesEdit = new FormProsesChemicalRawWbEdit();
prosesEdit.Tag = yourClass;
prosesEdit.ShowDialog();

您可以从 Tag 属性中获取该类的实例,如下所示:

yourClass = (YourClass) this.Tag;
this.proses_chemicalTableAdapter.FillByChemId(this.mcd_softwareDataSet.proses_chemical, yourClass.ProsesChemicalId1);

然而,使用 Tag 属性在表单中传递值通常是不好的做法,因为它需要大量的类型转换和了解每个标签中存储的内容。

更可靠的方法是使用构造函数注入,因为您知道要创建的表单的类型:

int value1 = this.proses_chemicalDataGridView1.Rows[e.RowIndex].Cells[1].Value;
int value2 = this.proses_chemicalDataGridView2.Rows[e.RowIndex].Cells[1].Value;

Form prosesEdit = new FormProsesChemicalRawWbEdit(value1, value2);  
prosesEdit.ShowDialog();

然后,您很可能必须将这些值存储为表单内的属性或字段。这是一种更稳健的方法,因为它可以防止意外更改。换句话说,如果您将来需要传递第三个值,那么您不太可能忘记更改需要更改的代码。

您也可以在这里使用属性注入,但我不确定您的要求,所以我将其留给您决定。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在C#中应用多个.Tag属性? 的相关文章

随机推荐