C# StreamWriter ,写入来自不同类的文件
本文关键字:同类 文件 StreamWriter | 更新日期: 2023-09-27 18:36:47
如何从不同的类写入文件?
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是必要的,并且如果您的代码引发,清理工作会变得复杂异常。
(或另一个类)中,您可以编写处理同一文件的方法,因为文件名在类 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.
}
}
您可以将 StreamWriter 对象作为参数传递。或者,您可以在流程方法中创建新实例。我还建议将StreamWriter包装在using
中:
public static void process(StreamWriter swObj)
{
using (swObj)) {
// Your statements
}
}
当然,
你可以简单地使用这样的"过程"方法:
public static void process()
{
// possible because of public class with static public members
using(StreamWriter mgraph = new StreamWriter(gen.m_graph_file))
{
// do your processing...
}
}
但从设计的角度来看,这将更有意义(编辑:完整代码):
public class Gen
{
// you could have private members here and these properties to wrap them
public string Id { get; set; }
public string GraphFile { get; set; }
}
public static void process(Gen gen)
{
// possible because of public class with static public members
using(StreamWriter mgraph = new StreamWriter(gen.GraphFile))
{
sw.WriteLine(gen.Id);
}
}
static void Main(string[] args)
{
Gen gen = new Gen();
gen.Id = args[1];
gen.GraphFile = @"msgrate_graph_" + gen.Id + ".txt";
process(gen);
}