c#帮助使值全局化

本文关键字:全局 帮助 | 更新日期: 2023-09-27 18:02:42

所以我理解如何使全局值和事实1。你不应该这么做。你不能使用在不同的"上下文"中创建的值,但是,我不确定如何在我的情况下纠正这个问题。我想如果你读一下我的代码就会明白了

            //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语句中得到错误:

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全局。谢谢你

c#帮助使值全局化

问题出在"dateTime"变量上。"userInput"是可以的,内部using语句可以访问外部using语句的作用域,因为内部using语句是外部using语句作用域的一部分。

问题是"dateTime"——变量是在while循环中声明的,在之后有一个using块——在变量不再可用之后,因为作用域被处置了——引用了一个不存在的变量。

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

不批评你的代码太多…这里有一个答案。你应该可以从这里走到

将变量声明与它的赋值

分开
string userInput = Console.ReadLine(); 

string userInput;
userInput = Console.ReadLine();

将声明(第一行)移出外层循环。

编辑:请,也看看属性(你可以叫他们全局变量)