2013-03-27 75 views
2

我有一個方法,我想在同一個c#項目中幾乎所有的類中使用。如何在其他類中使用方法?

public void Log(String line) 
{ 
    var file = System.IO.Path.GetPathRoot(Environment.SystemDirectory)+ "Logs.txt"; 

    StreamWriter logfile = new StreamWriter(file, true); 

    // Write to the file: 
    logfile.WriteLine(DateTime.Now); 
    logfile.WriteLine(line); 
    logfile.WriteLine(); 

    // Close the stream: 
    logfile.Close(); 
} 

什麼是在項目的其他類中重用此方法的方法?

+5

爲什麼不你使用log4net的任何其他日誌工具,而不是自己管理? – 2013-03-27 16:27:44

回答

7

如果你想在所有類使用它,然後使它static

你可以有一個staticLogHelper類,以更好地組織它,如:

public static class LogHelper 
{ 
    public static void Log(String line) 
    { 
     var file = System.IO.Path.GetPathRoot(Environment.SystemDirectory)+ "Logs.txt"; 

     StreamWriter logfile = new StreamWriter(file, true); 

     // Write to the file: 
     logfile.WriteLine(DateTime.Now); 
     logfile.WriteLine(line); 
     logfile.WriteLine(); 

     // Close the stream: 
     logfile.Close(); 
    } 
} 

然後通過執行LogHelper.Log(line)

+0

我想發佈帶有面向方面編程鏈接的答案,對於動態方面,使用PostSharp編譯時間方面的一些IoC容器攔截器。但似乎他所需要的只是一個「靜態」關鍵字...... – 2013-03-27 16:29:18

+0

@IlyaIvanov是的,雖然國際奧委會的容器是非常有用的**,但在這種情況下,它會是大錘打擊堅果。 – mattytommo 2013-03-27 16:30:27

+0

這工作,謝謝。 – Butters 2013-03-27 16:34:38

4

調用它可以使靜態類,並把這個功能在該類中。

public static MyStaticClass 
{ 
    public static void Log(String line) 
    { 
     // your code 
    } 
} 

現在你可以在別處叫它。 (無需實例,因爲它是一個靜態類)

MyStaticClass.Log("somestring"); 
相關問題