2014-09-28 25 views
-2

的線值我有一個文本文件,如下所示:創建一個函數來獲取在C#

NPSER NASER NQSER 
10 5 3 
JPNM EPNS RNPS 
12 10 11 
ACBE MNEF QPNS 
25 11 78 

這是我長久以來的數據簡化數據。我想自動查找NPSER,NASER,NQSER等的值。

到目前爲止,我的代碼如下:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 

namespace read_file 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      TextReader namefile = new StreamReader(@"E:\Code in C Sharp\read-file\read-file\test.txt"); 
      string line = namefile.ReadLine(); 
      Console.WriteLine(line); 
      Console.ReadLine(); 

      ////Read second line 
      string line1 = namefile.ReadLine(); 
      Console.WriteLine(line1); 
      Console.ReadLine(); 
     } 

     static public string[] Returnval(string line) 
     { 
      var Returnval = line.Split('\t'); 
      return Returnval; 
     } 
    } 
} 

我創建了一個功能Returnval,其分離這是製表符分隔的字符串。我想修改這個功能,會自動採取新的生產線作爲輸入,然後我應該能夠使用這樣的功能:

Returnval(NPSER, NASER, NQSER) 

我嘗試添加一個新行Returnval函數如下:

string line = namefile.Readline(); 

我得到一個錯誤,說名稱文件不在上下文中。

任何建議,非常感謝。

+0

您需要將namefile傳遞給您的函數。 – 2014-09-28 04:13:36

+0

namefile在您的Main函數中定義,並且您正試圖在Returnval函數中訪問它。您可以將'namefile'作爲參數傳遞給Returnval。 – brz 2014-09-28 04:15:28

+0

就我所見,你有很多問題。最有問題的可能是您似乎認爲NPSER可以用作變量名稱,只是因爲它被讀爲數據字符串。 C#不支持這種編程。 – RenniePet 2014-09-28 04:18:50

回答

2

Jdbaba,

如果我理解你的問題正確,你有一個變量範圍的問題。由於您在Main方法中聲明瞭namefile,因此只能在該方法中使用。如果你想其他方法中訪問它,你將需要聲明它的主要方法之外如下:

public static TextReader _namefile; 

static void Main(string[] args) 
{ 
    _namefile = new StreamReader(@"E:\Code in C Sharp\read-file\read-file\test.txt"); 
    string line = _namefile.ReadLine(); 
    Console.WriteLine(line); 
    Console.ReadLine(); 

    ////Read second line 
    string line1 = _namefile.ReadLine(); 
    Console.WriteLine(line1); 
    Console.ReadLine(); 
} 

static public string[] Returnval(string line) 
{ 
    string line1 = _namefile.ReadLine(); 
    var Returnval = line.Split('\t'); 
    return Returnval; 
} 

它通常是更好的做法是通過對象作爲參數傳遞給第二個方法類似

Returnval(namefile, NPSER, NASER, NQSER) 

,但聲明名稱文件作爲公共靜態變量適用於您的測試項目。

祝你好運!

+0

StreamReader應該處於「使用」狀態,因此它會被丟棄。 – RenniePet 2014-09-28 04:34:42

1

您應該添加TextReader作爲參數傳遞給函數,如下所示:

public static string[] Returnval(TextReader nameFile, string a, string b, string c) 
{ 
    string line = nameFile.ReadLine(); 
    //All your other code 
} 

然後從主,你可以把它作爲跟隨,通過你的StreamReader:

Returnval(nameFile, NPSER, NASER, NQSER); 

注意閱讀包含NPSER, NASER, NQSER的行不會自動爲您創建這些變體。由於他們都是字符串,但是,你很可能再次修改你的函數是:

public static string[] Returnval(TextReader nameFile, string[] myStrings) 
{ 
    string line = nameFile.ReadLine(); 
    //All your other code 
} 

,然後使用從主稱之爲:

Returnval(nameFile, line.Split('\t'); 

凡串line包含NPSER, NASER, NQSER由製表符分隔。

相關問題