2014-03-13 50 views
-6

當我運行我的應用程序時,出現以下錯誤。名稱fileitem在當前上下文中不存在錯誤

名稱的FileItem不會在目前情況下

public class foo 
{ 
    string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
    StreamReader fileitem; 
    StreamReader fileuser; 
    public foo() 
    { 
     fileitem = new StreamReader(Path.Combine(desktop, "one.txt")); 
     fileuser = new StreamReader(Path.Combine(desktop, "two.txt")); 
    } 
} 

public Form1() 
{ 
    InitializeComponent(); 
    for (int x = 0; x <= 8939500; x++) 
    { 
     lineuser = fileuser.ReadLine();    //The error line 
     if (!string.IsNullOrEmpty(lineuser)) 
    { 
      string[] values = lineuser.Split(' '); 
      int userid, factoriduser; 
      foreach (string value in values) 
    { 
........ 
+3

您的錯誤和代碼的該實例不匹配訪問fileuser。你在哪裏定義了代碼中的'lineuser'。 – Habib

+0

你在哪裏定義了'one'?文件「one.txt」是否存在?你有權限訪問它嗎? –

+0

在代碼的開頭。公共課foo之前。字符串lineuser; – user3403967

回答

0

存在創建的Class Foo一個實例,然後調用它是在這種情況下這樣的一個成員lineuser。您正嘗試訪問Class Foo這是錯誤的私人字段。如果不先實例化它們,則無法讀取該類的成員。要訪問私有字段,您需要聲明屬性。以下是你如何做到這一點的代碼。

public class foo 
    { 
     string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
     StreamReader fileitem; 
     StreamReader fileuser; 
     public lineUser{ 
      get{return fileuser;} 
      set{fileuser=Value;} 
     } 
     public foo() 
     { 
      fileitem = new StreamReader(Path.Combine(desktop, "one.txt")); 
      fileuser = new StreamReader(Path.Combine(desktop, "two.txt")); 
     } 
    } 



    public Form1() 
    { 
     InitializeComponent(); 
     for (int x = 0; x <= 8939500; x++) 
     { 
      Foo fo=new Foo(); 
      lineuser = fo.fileuser.ReadLine();    //The error line 
      if (!string.IsNullOrEmpty(lineuser)) 
      { 
       string[] values = lineuser.Split(' '); 
       int userid, factoriduser; 
       foreach (string value in values) 
       { 
+0

感謝您的回覆@AftabAhmed。但我得到了「fileuser」而不是「lineUser」的錯誤? – user3403967

+0

你的剩餘代碼在哪裏? –

+0

你可以爲fileuser創建另一個屬性 –

0

你必須創建的foo第一個實例,並通過foo

public Form1() { 
    InitializeComponent(); 
    // you have to create an instance of foo first: 
    var f = new foo(); 
    for (int x = 0; x <= 8939500; x++) { 
     // and access the fileuser through that instance of foo 
     lineuser = f.fileuser.ReadLine();    //The error line 
     if (!string.IsNullOrEmpty(lineuser)) { 
      string[] values = lineuser.Split(' '); 
      int userid, factoriduser; 
      foreach (string value in values){ 
       ........ 
相關問題