【问题标题】:C# StreamWriter , write to a file from different class?C# StreamWriter ,从不同的类写入文件?
【发布时间】:2012-06-14 19:42:28
【问题描述】:

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

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

【问题讨论】:

  • 你可以用 'n' 种方式来做...不要忘记以正确的方式来做...(请参阅我的建议;))

标签: c# class streamwriter


【解决方案1】:

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

【讨论】:

  • 请不要忘记关闭 StreamWriter(我更喜欢“使用”块)。
  • 1) gen 的目标是成为全局变量,可从所有类访问。什么是替代方案? 2)不需要在main方法中打开streamwriter?什么是替代方案?非常感谢!!我还在学习中
  • 正如我所说,如果 gen 类的目的是成为程序中随处使用的通用方法和属性的全局存储库,那么没有问题。只需将类声明为静态以明确您的意图。相反,对于 StreamWriter 对象,我会在每次需要写入内容时打开它,并在将每次写入保存在 try/catch 块下后立即关闭。
【解决方案2】:

当然,您可以像这样简单地使用“过程”方法:

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

【讨论】:

  • @John Ryann:我发布了一个完整的示例,以防你想尝试一下(对于那些你需要 .Net 4 的属性)
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2018-08-24
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 2014-02-14
    相关资源
    最近更新 更多