如何写入不同类的文件?
public class gen
{
public static string id;
public static string m_graph_file;
}
static void Main(string[] args)
{
gen.id = args[1];
gen.m_graph_file = @"msgrate_graph_" + gen.id + ".txt";
StreamWriter mgraph = new StreamWriter(gen.m_graph_file);
process();
}
public static void process()
{
<I need to write to mgraph here>
}
最佳答案
将 StreamWriter mgraph
传递给您的 process()
方法
static void Main(string[] args)
{
// The id and m_graph_file fields are static.
// No need to instantiate an object
gen.id = args[1];
gen.m_graph_file = @"msgrate_graph_" + gen.id + ".txt";
StreamWriter mgraph = new StreamWriter(gen.m_graph_file);
process(mgraph);
}
public static void process(StreamWriter sw)
{
// use sw
}
但是您的代码有一些难以理解的要点:
- 您使用两个静态变量声明类
gen
。这些变量是 在 gen 的所有实例之间共享。如果这是一个期望 客观,那就没问题了,就是有点疑惑。 - 您在主方法中打开 StreamWriter。这不是真的 给定静态 m_grph_file 是必要的,并且在您的代码引发时使清理复杂化 异常(exception)情况。
例如,在你的 gen 类中,(或在另一个类中)你可以编写在同一个文件上工作的方法,因为文件名在 gen 类中是静态的
public static void process2()
{
using(StreamWriter sw = new StreamWriter(gen.m_graph_file))
{
// write your data .....
// flush
// no need to close/dispose inside a using statement.
}
}
关于C# StreamWriter ,写入来自不同类的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10987949/