[英]C# StreamWriter , write to a file from different class?
如何寫不同類的文件?
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
類。 這些var在gen的所有實例之間共享。 如果這是一個令人討厭的目標,那么沒問題,但是我有點困惑。 例如,在您的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.
}
}
您可以將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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.