-1

我刚开始学习 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);
            }

        }
    }
}

就像我是初学者一样,我实际上是 3 天前才开始的。无论如何,我想做的是能够调用函数 EngineFeatures.txtedit.Write_txt("TXT/test.txt"); 在应用程序本身并让它返回一个字符串,但我仍然有点困惑,我还收到一条错误消息“EngineFeatures.txtedit.Write_txt(string, out string)':并非所有代码路径都返回一个值。” 我究竟做错了什么?

4

3 回答 3

6

如果出现异常,您的方法不会返回任何内容。添加一些默认值以向调用者返回或抛出(另一个)异常:

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);
}
于 2013-07-25T19:15:33.827 回答
2

您的代码中有几件事,首先您使用out关键字传递一个变量,然后返回相同的变量。您可以摆脱out参数列表中的 并简单地返回outputin try 块,但如果出现异常,您还应该返回一些值,可能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;
    }
}
于 2013-07-25T19:18:00.060 回答
0
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;

    }
于 2016-03-02T19:06:35.927 回答