我有一个 C# winform 应用程序,它正在进行大量计算。有一个“运行”按钮来触发该过程。我希望能够“重新触发或重新运行或重新提交”信息,而无需重新启动程序。问题是我有很多变量需要重置。有没有办法取消定义(重置)所有参数?
private Double jtime, jendtime, jebegintime, javerage, .... on and on
创建一个存储这些变量的对象实例。引用这个对象,当想要“重置”时,重新实例化你的对象。例如
public class SomeClass
{
public double jTime;
...
}
...
SomeClass sc = new SomeClass();
sc.jTime = 1;
sc = new SomeClass();
最好的方法是如果你把它们都放在一个班级里。
然后在重置时,您只需创建一个具有初始化值的新类。
你可以使用反射;尽管反射的性能不如其他建议的解决方案,但我并不完全确定您的解决方案域,反射可能是一个不错的选择。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Data data = new Data();
//Gets all fields
FieldInfo[] fields = typeof(Data).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (var field in fields)
{
//Might want to put some logic here to determin a type of the field eg: (int, double)
//etc and based on that set a value
//Resets the value of the field;
field.SetValue(data, 0);
}
Console.ReadLine();
}
public class Data
{
private Double jtime, jendtime, jebegintime, javerage = 10;
}
}
}
是的,只需使用 Extract Method 重构技术。基本上在单独的方法中提取重置逻辑,然后在需要时调用它
private void ResetContext()
{
jtime = jendtime = jebegintime = javerage = 0;
}