C# 控件状态怎么用静态方法分离出来
如题,每个窗体内的控件太多 ,程序代码太长,我想用静态方法把他分离出来。但是普通类又没办法获取控件,这个要怎么弄呢?
/// <summary>
/// 打开目录
/// </summary>
/// <param name="folderPath">目录路径(比如:C:\Users\Administrator\)</param>
private static void OpenFolder(string folderPath)
{
if (string.IsNullOrEmpty(folderPath)) return;
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
psi.Arguments = folderPath;
process.StartInfo = psi;
try
{
process.Start();
}
catch (Exception ex)
{
throw ex;
}
finally
{
process?.Close();
}
}
/// <summary>
/// 打开目录且选中文件
/// </summary>
/// <param name="filePathAndName">文件的路径和名称(比如:C:\Users\Administrator\test.txt)</param>
private static void OpenFolderAndSelectedFile(string filePathAndName)
{
if (string.IsNullOrEmpty(filePathAndName)) return;
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
psi.Arguments = "/e,/select,"+filePathAndName;
process.StartInfo = psi;
//process.StartInfo.UseShellExecute = true;
try
{
process.Start();
}
catch (Exception ex)
{
throw ex;
}
finally
{
process?.Close();
}
}
/// <summary>
/// 打开文件
/// </summary>
/// <param name="filePathAndName">文件的路径和名称(比如:C:\Users\Administrator\test.txt)</param>
/// <param name="isWaitFileClose">是否等待文件关闭(true:表示等待)</param>
private static void OpenFile(string filePathAndName,bool isWaitFileClose=true)
{
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo(filePathAndName);
process.StartInfo = psi;
process.StartInfo.UseShellExecute = true;
try
{
process.Start();
//等待打开的程序关闭
if (isWaitFileClose)
{
process.WaitForExit();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
process?.Close();
}
}
问题描述中提到想使用静态方法将控件状态分离出来,但是普通类无法获取控件。可以通过以下几步来实现该功能:
public static class ControlStateManager
{
public static bool CheckBox1Visible { get; set; }
public static string TextBox1Text { get; set; }
// 其他控件的状态...
}
private void Form1_Load(object sender, EventArgs e)
{
checkBox1.Visible = ControlStateManager.CheckBox1Visible;
textBox1.Text = ControlStateManager.TextBox1Text;
// 设置其他控件的状态...
}
private void Form1_Closing(object sender, CancelEventArgs e)
{
ControlStateManager.CheckBox1Visible = checkBox1.Visible;
ControlStateManager.TextBox1Text = textBox1.Text;
// 保存其他控件的状态...
}
这样,每次窗体加载时,就会使用静态类中保存的控件状态来更新控件的状态。当窗体关闭时,会将当前控件的状态保存到静态类中,下次打开窗体时再次使用这些状态。
这种方法可以在静态类中定义多个字段来保存不同的控件状态,以满足多种需求。另外,如果有很多窗体都需要使用这种控件状态分离的方式,可以将静态类定义在公共的类库中,供所有窗体使用。
要么用静态类定义 继承, 要么改为 c# +html 混编