2011-07-16 52 views
3

我目前正在與while循環內聲明一個公共字符串,因爲我想在其他方法如何while循環內聲明一個公共字符串(C#)

字符串使用它(串)問題是「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; 
       } 
      } 
     } 
    } 
} 
+0

你會如何使用它從其他方法?這是一個線程場景嗎? –

回答

4

不能聲明在方法內部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; 
       } 
      } 
     } 
    } 
} 
+0

非常感謝! – James

+0

@詹姆斯歡迎您。不要忘記upvote並接受:) – VMAtm

+0

我認爲有人不喜歡我們?在有效答案downvotes –

0

你應該創建一個全局變量並分配,而不是例如

public class MyClass 
{ 
    public string s; 
    private void CheckLog() { ... } 
} 

在任何方法中,你可以使用它注意檢查s.IsNullOrEmpty(),以避免收到一個NullPointerException(也是我假設字符串應該包含某些東西)。

0

最好將字符串作爲by-ref參數傳遞給函數,或者從函數返回。聲明它爲成員似乎不是一個好主意。

public string CheckLog(){}