c# 帮助使值全局化

c# Help making values global

所以我了解如何创建全局值以及以下事实:1. 您不应该这样做,并且 2. 您不能使用在不同 "context" 中创建的值,但是,我不是确定如何在我的案例中纠正这个问题。我认为如果你阅读我的代码就会有意义

            //read in Load Query TestCSV
        var sourcePath = @"D:\Load Query test.csv"; //What is the inital CSV
        var delimiter = ",";
        var firstLineContainsHeaders = true; //CSV has headers
        //creates temp file which takes less time than loading into memory
        var tempPath = Path.Combine(@"D:", Path.GetRandomFileName());
        var lineNumber = 0;

        var splitExpression = new Regex(@"(" + delimiter + @")(?=(?:[^""]|""[^""]*"")*$)");

        using (var writer = new StreamWriter(tempPath))
        using (var reader = new StreamReader(sourcePath))
        {
            string line = null;
            string[] headers = null;
            if (firstLineContainsHeaders)
            {
                line = reader.ReadLine();
                lineNumber++;

                if (string.IsNullOrEmpty(line)) return; // file is empty;

                headers = splitExpression.Split(line).Where(s => s != delimiter).ToArray();

                writer.WriteLine(line); // write the original header to the temp file.
            }
            var i = 0; //used in 2nd while loop later
            string lines = null;//used in next using statement
            while ((line = reader.ReadLine()) != null)
            {
                lineNumber++;

                var columns = splitExpression.Split(line).Where(s => s != delimiter).ToArray();

                //make sure you always have the same number of columns in a line
                if (headers == null) headers = new string[columns.Length];

                if (columns.Length != headers.Length) throw new InvalidOperationException(string.Format("Line {0} is missing one or more columns.", lineNumber));
                string badDate = "Date entered incorrectly";                                    //used in next while loop
                // this while loop will read in the user input dateTime and use that to get the column from the PI server.
                //if the date time is entered incorrectly it will tell the user to try to input the datetime again
                while (i==0)
                {
                    Console.WriteLine("Enter date, ex:16 Jun 8:30 AM 2008, Press enter when done"); //instruct the user in how to enter the date
                    string userInput = Console.ReadLine(); //read in the date the user enters
                    string format = "dd MMM h:mm tt yyyy"; //how the system will read the date entered

                    DateTime dateTime;

                    //if date is entered correctly, parse it, grab the parsed value dateTime and exit loop
                    if (DateTime.TryParseExact(userInput, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
                    {                           
                        i = 1; //set the flag to exit while loop
                    }
                    //if input is bad return "Date entered incorrectly and run the loop again
                    else
                    {
                        Console.WriteLine(badDate);
                        i=0; //set the flag to run the loop again
                    }
                }
                var del = ",";                                                                  //used in next using statement
                var SplitExpression = new Regex(@"(" + del + @")(?=(?:[^""]|""[^""]*"")*$)");   //used in next using statement
                //Use the dateTime from the previous while loop and use it to add each point in "testpts.csv" to "Load Query Test.csv"
                using (StreamReader tags = new StreamReader(@"D:\testpts.csv"))
                {
                   // string userInput = Console.ReadLine();
                    string format = "dd MMM h:mm tt yyyy";
                    DateTime.TryParseExact(userInput, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
                    lines = tags.ReadLine();
                    var columns1 = SplitExpression.Split(lines).Where(s => s != del).ToArray();
                    var point = PIPoint.FindPIPoint(piServer, lines);
                    var value = point.RecordedValue(dateTime);
                    string returnXml = string.Format(@"<value=""{0}"" />", value);
                    columns[15] = columns[15].Replace("0", returnXml); //column the point should be placed in (in Load Query Test.csv)
                }
                //if statement that will replace any extra 0 testpt values with column 13 values
                if (columns[15].Contains("0"))
                {
                    columns[15] = columns[15].Replace("0", columns[13]);
                }

                writer.WriteLine(string.Join(delimiter, columns));
            }

        }

        File.Delete(sourcePath); //delete the original csv
        File.Move(tempPath, sourcePath); //replace the old csv with edited one

        Console.ReadLine();

我在使用语句中遇到错误:

using (StreamReader tags = new StreamReader(@"D:\testpts.csv"))
                {
                   // string userInput = Console.ReadLine();
                    string format = "dd MMM h:mm tt yyyy";
                    DateTime.TryParseExact(userInput, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
                    lines = tags.ReadLine();
                    var columns1 = SplitExpression.Split(lines).Where(s => s != del).ToArray();
                    var point = PIPoint.FindPIPoint(piServer, lines);
                    var value = point.RecordedValue(dateTime);
                    string returnXml = string.Format(@"<value=""{0}"" />", value);
                    columns[15] = columns[15].Replace("0", returnXml); //column the point should be placed in (in Load Query Test.csv)
                }

在这种情况下,dateTime 和 userInput 值显然不符合上下文。我需要在前面的 while 循环中创建它们,但是因为我希望用户只能输入一次正确的日期并确保输入正确以确保脚本实际提取数据。

请告诉我是否有其他方法可以订购我的代码或如何使 userInput 和 dateTime 全局化。谢谢

您的问题出在“dateTime”变量上。 “userInput”很好,内部 using 语句可以访问其外部 using 语句的范围,因为内部 using 语句是外部范围的一部分。

问题出在“dateTime” - 变量在 while 循环内声明,并且有一个 using 块 afterwards -在变量不再可用之后,因为范围已被释放 - 它引用了一个不存在的变量。

解决方案:将 dateTime 变量的声明移出 while。比方说,while 定义前的一行。

不用过多批评您的代码……这里是一个答案。从这里开始你应该可以自己走路了

将变量的声明与其赋值分开

string userInput = Console.ReadLine(); 

string userInput;
userInput = Console.ReadLine();

将声明(第一行)移到外循环之外。

Edit: Please, also have a look at Properties (you may call them globals)