繁体   English   中英

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

[英]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的所有实例之间共享。 如果这是一个令人讨厌的目标,那么没问题,但是我有点困惑。
  • 您可以在主要方法中打开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.
    } 
}

您可以将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM