0

このコードの何が問題なのか、理解してください。(テキスト ファイルから 1 行ずつ文字列の一部を取得して、文字列を作成しようとしています)。

行に「オブジェクト参照のインスタンスではオブジェクトが設定されていません」という実行時エラーが表示されますstrbuild.Append(str);

        StreamReader reader = new StreamReader("buf.txt", System.Text.Encoding.ASCII);
        StringBuilder strbuild = new StringBuilder();
        strbuild = null;

        while (reader.Peek() >= 0)
        {
            string str = null;
            str = reader.ReadLine().ToString();

            string segment = str.Substring(0, 1);

            if (segment == "A")
            {
                strbuild.Append(str); //here  i get an error
            }
            else if (segment == "B")
            {
                strbuild.Append("BET");
            }

        }
        printstr = strbuild.ToString();
        reader.Close();

        MessageBox.Show(printstr);
4

4 に答える 4

10

次の行を見てください。

StringBuilder strbuild = new StringBuilder();
strbuild = null;

を呼び出したときに何が起こると思いますstrbuild.Append(...)? なぜあなたstrbuildはまったくnullに設定していますか?

あなたは 2 行の変数の初期化が好きなようです。別の例を次に示します。

string str = null;
str = reader.ReadLine().ToString();

これは、次のようにするとより読みやすくなります。

string str = reader.ReadLine();

(ReadLineすでに文字列を返しているため、結果を呼び出す必要はありませんToString()。)

ただし、 - にはステートメントを使用することをお勧めします。そうしないと、例外がスローされたときに、リーダーを開いたままにすることになります。usingStreamReader

良い点の 1 つTextReader.ReadLine()は、完了時に null を返すことです。のぞいてから読む必要はありません。

最後に、単一文字のみをテストする場合は、部分文字列は必要ありません。文字列インデクサーを使用して文字を取得するだけです。したがって、次のようにすることができます。

StringBuilder builder = new StringBuilder();

// Consider using File.OpenText
using (StreamReader reader = new StreamReader("buf.txt", Encoding.ASCII))
{
    string line;
    // Normally side-effect + test is ugly, but this is a common and
    // neat idiom
    while ((line = reader.ReadLine()) != null)
    {
        // TODO: What do you want to happen for empty lines?
        char segment = str[0];
        if (segment == 'A')
        {
            builder.Append(line);
        }
        else if (segment == 'B')
        {
            builder.Append("BET");
        }
    }
}
MessageBox.Show(builder.ToString());
于 2010-03-02T14:55:13.313 に答える
6

初期化後に stringbuilder を null に設定しています。

変化する

StringBuilder strbuild = new StringBuilder(); 
strbuild = null; 

StringBuilder strbuild = new StringBuilder(); 

線を抜く

strbuild = null;
于 2010-03-02T14:55:05.547 に答える
2

変化する

  StringBuilder strbuild = new StringBuilder();
  strbuild = null;

  StringBuilder strbuild = null;
  strbuild = new StringBuilder();

または、この種のエラーを防ぐには:

  StringBuilder strbuild = new StringBuilder();
于 2010-03-02T14:55:56.933 に答える
1

あなたの例にはいくつかのエラーがあります。最初に修正されたバージョンは次のとおりです。

StringBuilder strbuild = new StringBuilder();

// Put resource into using statements, for deterministic cleanup
using (TextReader reader = new StreamReader("buf.txt", System.Text.Encoding.ASCII))
{
    string line;

    //Maybe looks a little ugly the first time, but is commonly used to
    //process all the lines of a file (.ReadToEnd() can cause memory problems
    //on really big files)
    while ((line = reader.ReadLine()) != null)
    {
        //Instead of if, else if, else if, etc just take a switch
        //statement. Makes it much easier to read.
        switch (line[0])
        {
            //If you need case insensitivity put both versions of the character
            //before your first line of code
            case 'A':
            case 'a':
                strbuild.Append(line);
                break;
            //Otherwise just use the lower or upper case version you like
            case 'B':
                strbuild.Append("BET");
                break;
        }
    }
}

//Put the result of the StringBuilder directly into the Show() function
MessageBox.Show(strbuild.ToString());
于 2010-03-02T15:06:55.290 に答える