簡體   English   中英

在方法上需要幫助

[英]Need help on a method

我剛剛開始學習C#,並且我正在嘗試制作一個控制台應用程序,該應用程序將讀取文本文件並將其顯示在命令提示符下。 我還試圖制作一種在單獨的dll中讀取文本文件的方法,因為我計划稍后擴展程序並嘗試制作一種基於文本的游戲引擎。 無論如何,這是我的dll中的代碼:

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

namespace EngineFeatures
{
    public class txtedit
    {

        public string Write_txt(string textin, out String output)
        {
            try
            {
                 using (StreamReader sr = new StreamReader(textin))
                {


                    String line = sr.ReadToEnd();
                    output = line;
                    return output;
                }

            }
             catch (Exception e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }

        }
    }
}

就像我是一個初學者一樣,我從三天前才開始。 無論如何,我想做的是能夠調用函數EngineFeatures.txtedit.Write_txt(“ TXT / test.txt”); 在應用程序本身中並返回一個字符串,但我仍然有些困惑,並且我還收到一條錯誤消息,提示“ EngineFeatures.txtedit.Write_txt(string,out string)':並非所有代碼路徑都返回一個值。” 我究竟做錯了什么?

如果發生異常,則您的方法沒有返回任何內容。 添加一些默認值以返回或引發(另一個)異常給調用者:

catch (Exception e)
{
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
    return null; 
    // or: return String.Empty
    // or: throw new GameLoadException("Cannot read game file", e);
}

您的代碼中包含兩件事:首先,您要使用out關鍵字傳遞變量,然后返回相同的變量。 您可以擺脫參數列表中的out ,而只需在try塊中返回output ,但是在出現異常的情況下,您還應該返回一些可能為null例如:

編輯:您可以完全擺脫output參數,而只需返回該行。 (感謝@Jim)

public string Write_txt(string textin)
{
    try
    {
        using (StreamReader sr = new StreamReader(textin))
        {
            String line = sr.ReadToEnd();
            return line;
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
        return null;
    }
}
public class txtedit
{

    public string Write_txt(string textin, out String output)
    {
        output = "";

        try
        {
            using (StreamReader sr = new StreamReader(textin))
            {


                String line = sr.ReadToEnd();
                output = line;
                return output;
            }


        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
        return output;

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM