我目前正试图在一个while循环中声明一个公共string,因为我想在其他方法中使用它(string)
有问题的string是“s”
private void CheckLog() { bool _found; while (true) { _found = false; Thread.Sleep(5000); if (!System.IO.File.Exists("Command.bat")) continue; using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat")) { string s = ""; while ((s = sr.ReadLine()) != null) { if (s.Contains("mp4:production/CATCHUP/")) { _found = true; break; } } } } }
你不能在方法中声明public
字符串。 尝试这个:
string s = ""; private void CheckLog() { bool _found; while (true) { _found = false; Thread.Sleep(5000); if (!System.IO.File.Exists("Command.bat")) continue; using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat")) { //s = "VALUE"; while ((s = sr.ReadLine()) != null) { if (s.Contains("mp4:production/CATCHUP/")) { _found = true; break; } } } } }
你应该创建一个全局变量,然后赋值
public class MyClass { public string s; private void CheckLog() { ... } }
在任何方法你可能会使用它记得检查是否s.IsNullOrEmpty()
以避免得到一个NullPointerException(也我假设该字符串应该包含的东西)。
最好将字符串作为by-ref参数传递给函数,或者从函数返回。 宣布它成员似乎不是一个好主意。
public string CheckLog(){}