简体   繁体   English

C#取消定义所有参数的快速方法

[英]c# Quick way to undef all parameters

I have a C# winform app which is doing a lot of calculation. 我有一个进行大量计算的C#winform应用程序。 there is a "run" button to trigger the process. 有一个“运行”按钮来触发该过程。 I would like to be able to "re-trigger or re-run or re-submit" the information without having to restart the program. 我希望能够“重新触发或重新运行或重新提交”信息,而不必重新启动程序。 Problem is I have a lot of variables that need to be reset. 问题是我有很多需要重置的变量。 Is there a way to undef (reset) all parameters? 有没有办法取消定义(重置)所有参数?

private Double jtime, jendtime, jebegintime, javerage, .... on and on

Create an instance of an object that stores these variables. 创建一个存储这些变量的对象的实例。 Reference this object, and when wanting to "reset", reinstantiate your object. 引用该对象,然后在要“重置”时重新实例化您的对象。 eg 例如

public class SomeClass
{
   public double jTime;
   ...
}

...

SomeClass sc = new SomeClass();
sc.jTime = 1;
sc = new SomeClass();

The best way would have been if you had them all in a class. 最好的方法是,如果您在一堂课中都将它们都包含在内。
Then on reset you'd just create a new class with initialized values. 然后在重置时,您只需创建一个带有初始化值的新类。

You could use Reflection; 您可以使用反射; although Reflection is the less performant than the other proposed solutions, but I am not entirely sure of your solution domain and Reflection might be a good option. 尽管Reflection比其他提议的解决方案性能差,但是我不确定您的解决方案领域,Reflection可能是一个不错的选择。

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;
        }
    }
}

Yes, simply use Extract Method refactoring technique. 是的,只需使用提取方法重构技术即可。 Basically extract reset logic in a separate method and then just call it when need 基本上在单独的方法中提取复位逻辑,然后在需要时调用它

private void ResetContext()
{
   jtime = jendtime = jebegintime = javerage = 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM