C# 需要方法上的帮助吗
我刚刚开始学习c,我正在尝试制作一个控制台应用程序,它将读取文本文件并在命令提示符下显示。我也在尝试在一个单独的dll中读取文本文件的方法,因为我计划以后扩展我的程序,并尝试制作一种基于文本的游戏引擎。无论如何,这是我的dll中的代码:C# 需要方法上的帮助吗,c#,string,methods,input,output,C#,String,Methods,Input,Output,我刚刚开始学习c,我正在尝试制作一个控制台应用程序,它将读取文本文件并在命令提示符下显示。我也在尝试在一个单独的dll中读取文本文件的方法,因为我计划以后扩展我的程序,并尝试制作一种基于文本的游戏引擎。无论如何,这是我的dll中的代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace EngineFeatures {
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\u txtTXT/test.txt;在应用程序本身中,让它返回一个字符串,但我仍然有点困惑,并且我还收到一个错误,即EngineFeatures.txtedit.Write_txtstring,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块中返回输出,但如果出现异常,您还应该返回一些可能为null的值,如: 编辑:您可以完全删除输出参数,只需返回行即可。感谢@Jim
错误信息应清晰;如果try块中发生异常,它将不会返回任何内容,因为您在其他任何地方都没有其他返回语句。您的问题标题并不能真正解释您的问题是什么。您应该给出一个更具描述性的标题。答案很好,但在您的示例中,您可以更进一步,只需去掉第二个参数输出,然后返回sr.ReadToEnd@吉姆,是的,但实际上我想传达的是,无论是“尝试”还是“抓住”块,都应该返回一些东西。但是你说得对,我将修改它。我通常在try块之外声明要返回的对象,而不是从try块和catch块返回,并在catch结束后返回它。所以我要让string output=string.Empty;就在尝试之前。然后设置output=sr.ReadToEnd;从try内部,然后在捕获之后返回输出;在catch中,您可以将输出设置为null,或者将其设置为string.empty,或者抛出新异常,等等。但是,从try/catch之外返回意味着您只需要一个return语句,而不需要为每个catch单独使用一个return语句。
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;
}