需要一些帮助使用类。 (C#Winforms) [英] Need a little help using classes. (C# Winforms)
问题描述
好的,我正在使用一个带有大约28个复选框的表单和一个按钮来移动/重命名这样的文件:
Okay, so, I'm using a form with about 28 checkboxes and a button to move/rename a file something like this:
private void button3_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
string destFile = "C:\Testing\" + selectDept + "AB"
+ dateVariable + ".pdf";
File.Move(myFile, destFile);
}
if (checkBox2.Checked)
{
string destFile = "C:\Testing\" + selectDept + "ZZ"
+ dateVariable + ".pdf";
File.Move(myFile, destFile);
}
if (checkBox3.Checked)
{
string destFile = "C:\Testing\" + selectDept + "QQ"
+ dateVariable + ".pdf";
File.Move(myFile, destFile);
}
if (checkBox4.Checked)
{
string destFile = "C:\Testing\" + selectDept + "XY"
+ dateVariable + ".pdf";
File.Move(myFile, destFile);
}
}
那么是否有一种方法可以使用一个类,这样我就可以使用一些更干净的代码了除了几件事之外,还要做27个几乎相同的IF语句?
So is there a way to use a class so that I have some cleaner code that doesn't involve doing 27 IF statements that are almost the same except for a couple of things?
推荐答案
这是一种可能性。
Here's one possibility.
使用移动文件的方法创建一个包含复选框和部门后缀的类。类似的东西。
Create a class that holds a checkbox and the department suffix, with method that moves the file. Something like so.
public class CheckBoxFile
{
CheckBox checkbox;
string departmentSuffix;
public CheckBoxFile(CheckBox box, string dept)
{
checkbox = box;
departmentSuffix = dept;
}
public MoveFile(string myFile, string selectDept, string dateVariable)
{
if(checkbox.Checked)
{
string destFile = "C:\Testing\" + selectDept + departmentSuffix
+ dateVariable + ".pdf";
File.Move(myFile, destFile);
}
}
}
加载表单时,将每个复选框放入列表中。然后,在按钮单击方法中,只需循环遍历每个元素上调用MoveFile的列表。
When the form loads, put each checkbox into a list. Then, in your button click method, just loop through the list calling MoveFile on each element.
这篇关于需要一些帮助使用类。 (C#Winforms)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!