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

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

最佳答案

将 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 是必要的,并且在您的代码引发时使清理复杂化 异常(exception)情况。

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

关于C# StreamWriter ,写入来自不同类的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10987949/

相关文章:

php - 根据页面名称添加类元素

java - 如何对输入和输出流使用 for 循环?

c# - 如果文件已经存在,如何覆盖?

c# - 我的 VS 2013 应用程序应该包含哪个 C++ 合并模块

c# - Web API 获取多部分/表单数据响应的最简单方法

c# - T4 模板 - 从实现接口(interface)的类生成单元测试类

javascript - 我应该如何在 JS 类中声明属性?

java - 我应该使用额外的类或设计实例的样式吗?

c# - 如何正确使用 StreamWriter 类?

c# - WCF- "The request for security token could not be satisfied because authentication failed"