C#StreamWriter,写入来自不同类的文件?

时间:2012-06-11 21:43:05

标签: c# class streamwriter

如何写入不同类的文件?

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>
}

3 个答案:

答案 0 :(得分:4)

将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的实例之间共享。如果这是一个渴望 客观,那没问题,但我有点疑惑。
  • 您在main方法中打开StreamWriter。这不是真的 必要时给定静态m_grph_file,并在代码提升的情况下使清理复杂化 异常。

例如,在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.
    } 
}

答案 1 :(得分:2)

您可以将StreamWriter对象作为参数传递。或者,您可以在流程方法中创建新实例。我还建议将StreamWriter包装在using

public static void process(StreamWriter swObj)
{
  using (swObj)) {
      // Your statements
  }
}

答案 2 :(得分:1)

当然,你可以简单地使用这样的'过程'方法:

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); 
}