Question

I have a method that I want to use in almost all the classes within a same c# project.

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

What is the approach to reuse this method in other classes of the project?

Était-ce utile?

La solution

If you want to use it in all classes, then make it static.

You could have a static LogHelper class to better organise it, like:

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

Then call it by doing LogHelper.Log(line)

Autres conseils

You can make a static class and put this function in that class.

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

Now you can call it elsewhere. (No need to instantiate because it's a static class)

MyStaticClass.Log("somestring");

You can use Extrension method in statis class

Sample on string extension

public static class MyExtensions
    {
        public static int YourMethod(this String str)
        {
        }
    }  

link : http://msdn.microsoft.com/fr-fr/library/vstudio/bb383977.aspx

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top