【发布时间】:2021-11-23 20:34:56
【问题描述】:
对不起,我写得很糟糕的标题,我是一个初学者程序员,我刚开始使用 c# winforms 应用程序。在一个函数中,我创建了某种类型的对象,然后在其他函数中,我遍历了该类型对象的列表,但是我正在切换我正在使用的控件类型,当我这样做时,我必须更改类型在二十多个地方声明我的目标。有没有办法创建一个保存该类型的变量,而不是定义该变量的所有对象,所以我只需指定一次类型,然后更改该变量。因为我使用 winforms 控件作为我的类类型,所以无论我的对象是什么类型,我调用的所有函数都是相同的,所以我需要做的就是更改类型声明,仅此而已,对不起,如果这是一个愚蠢的问题任何帮助将不胜感激。
这是我的上下文代码的 sn-p:
private void function1(object sender, EventArgs e) //not my actual function because the real function has lots of other unrelated code
{
ListView PlaceType = new ListView(); // these ListView types i would like to replace with a placeholder if possible
ListView listview = new ListView();
int count2 = autolayoutGroups.Controls.OfType<ListView>().ToList().Count();
listview.Size = new System.Drawing.Size(150, 100);
listview.BackColor = normalColor;
listview.BorderStyle = BorderStyle.Fixed3D;
listview.ForeColor = System.Drawing.Color.Black;
listview.Name = "Group" + count2;
listview.MouseDown += Select;
}
private void function2(object sender, EventArgs e)
{
List<ListView> list_of_groups = autolayoutGroups.Controls.OfType<ListView>().ToList(); // a place where I need some type of placeholder
foreach (ListView l in list_of_groups)
{
// do something here
}
}
private void function3(object sender, EventArgs e) // I have several functions like this
//and if I change the control I'm using I have to change the types in every function
{
List<ListView> list_of_groups = autolayoutGroups.Controls.OfType<ListView>().ToList(); // a place where I need some type of placeholder
foreach (ListView l in list_of_groups)
{
// do something here
}
}
【问题讨论】:
-
我正在切换我正在使用的控件类型 - 多久一次?
-
我不确定,到目前为止可能有 4-5 次,而且很高兴知道未来,我记得不久前的一些编程课,如果你必须更改相同的值然后在几个地方用变量替换该值。