2013-03-27 37 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");