2

如何从不同的类写入文件?

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

3 回答 3

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.
    } 
}
于 2012-06-11T21:48:05.607 回答
2

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

public static void process(StreamWriter swObj)
{
  using (swObj)) {
      // Your statements
  }
}
于 2012-06-11T21:58:39.753 回答
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); 
}
于 2012-06-11T21:56:46.537 回答