2012-06-11 113 views
2

如何寫入不同類文件?C#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> 
} 
+0

你可以做到這一點在「N」的方式,不要忘記做正確的方式...(見我的建議;)) – Learner

回答

4

傳遞的StreamWriter mgraphprocess()方法

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,這並不是真正的 ,並且如果代碼引發 異常,清理會變得複雜。

例如,在你根類(或其他類),你可以寫在同一個文件的工作方式,因爲文件名中的類是靜態的根

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

請不要忘記關閉StreamWriter(我更喜歡「使用」塊)。 – kol

+0

1)gen的目標是全局變量,可以從所有類訪問。有什麼選擇? 2)主要方法中不需要打開streamwriter?有什麼選擇?非常感謝!!我仍然在學習 –

+0

正如我所說,如果gen類的目的是成爲程序中無處不在的通用方法和屬性的全局存儲庫,那麼就沒有問題了。只要聲明這個類是靜態的就可以明確你的意圖。對於StreamWriter對象,我會在每次寫入某個try/catch塊之後立即寫入內容並立即關閉時打開它。 – Steve

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

@John Ryann:我發佈了一個完整的例子,如果你想嘗試一下(對於那些你需要.Net 4的屬性) – Learner

2

您可以傳遞一個StreamWriter對象作爲參數。或者,您可以在流程方法中創建一個新實例。我還建議包裹裏面你的StreamWriter一個using

public static void process(StreamWriter swObj) 
{ 
    using (swObj)) { 
     // Your statements 
    } 
} 
相關問題