2017-05-01 1 views
-2

코드 조각을 쓰려고하는데, 관련된 내용 중 하나는 .txt 파일에서 한 행씩 읽는 것입니다. 그러나 '개체 참조가 필요합니다'오류가 계속 발생합니다. 파일을 읽는 것만으로도 많은 문제가 발생할 수는 있지만 어떻게되는지는 알 수 없습니다. 여기에 내 코드 (바로 시작하기 전에 주석 비트를 무시)입니다 :Visual Studio에서 파일을 읽을 수 없습니다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO; 
using System.Text.RegularExpressions; 
//(Program) 
namespace FileReader 
{ 
class ReadFromFile 
{ 
    public void IsValidLine(string text) 
    { 
     Regex rgx = new Regex(@"^([A-Za-z]{1,5})((\s\d){0,9})(\s*)$"); 
     if (rgx.IsMatch(text) == false) 
     { 
      Console.WriteLine("Invalid Format"); 
     } 

    } 
    static void Main() 
    { 
     System.IO.StreamReader file = new 
System.IO.StreamReader(@"C:\Users\Public\TestFolder\WriteLines2.txt"); 
     { 
      int counter = 0; 
      string line; 
      List<string> lines = new List<string>(); 


      while ((line = file.ReadLine()) != null) 
      { 
       //HERE IS THE ERROR 
       IsValidLine(line); 
       lines.Add(line); 
       counter++; 
      } 
     } 
    } 
} 
+1

'public void IsValidLine (문자열 텍스트)'를'public static void IsValidLine (문자열 텍스트)'로 변경하십시오. 'static' 키워드가 없을 때'IsValidLine' 메소드를 사용하려면'ReadFromFile' 클래스의 인스턴스가 필요합니다. static 키워드를 추가하면 방금 말한 내용을 알 수 있습니다. – Quantic

+0

그래, 고마워. –

답변

0

문제는 정적 컨텍스트에서 비 정적 클래스에 액세스하는 것입니다 - 따라서 해당 클래스의 개체에 대한 참조를 필요로했다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO; 
using System.Text.RegularExpressions; 
//(Program) 
namespace FileReader 
{ 
class ReadFromFile 
{ 
    public static void IsValidLine(string text) 
    { 
     Regex rgx = new Regex(@"^([A-Za-z]{1,5})((\s\d){0,9})(\s*)$"); 
     if (rgx.IsMatch(text) == false) 
     { 
      Console.WriteLine("Invalid Format"); 
     } 

    } 
    static void Main() 
    { 
     System.IO.StreamReader file = new 
System.IO.StreamReader(@"C:\Users\Public\TestFolder\WriteLines2.txt"); 
     { 
      int counter = 0; 
      string line; 
      List<string> lines = new List<string>(); 


      while ((line = file.ReadLine()) != null) 
      { 
       //HERE IS THE ERROR 
       IsValidLine(line); 
       lines.Add(line); 
       counter++; 
      } 
     } 
    } 
} 

정적뿐만 아니라 클래스를 만들기 위해 이러한 오류를 내가 좋을 것 방지하려면 :

static class ReadFromFile 
//... 

그런 다음 코드는 컴파일되지 않습니다 그래서 당신이해야 할 모든 정적 방법을 확인하는 것입니다 클래스에 정적이 아닌 것이 있으면.

+0

@GeorgeBouverie가이 문제를 해결 했습니까? 그렇게했다면, 답을 올바른 답으로 표시하는 것을 잊지 마십시오. 그러면 귀하와 더 많은 커뮤니티가 해결 된 문제를 식별하는 데 도움이됩니다. – MetaColon

관련 문제