C# 如何在其他类中使用方法?

C# 如何在其他类中使用方法?,c#,wpf,methods,code-reuse,C#,Wpf,Methods,Code Reuse,我有一个方法,我想在同一个c#项目中的几乎所有类中使用 在项目的其他类中重用此方法的方法是什么?如果要在所有类中使用此方法,请将其设置为静态 您可以使用一个staticLogHelper类来更好地组织它,例如: public static class LogHelper { public static void Log(String line) { var file = System.IO.Path.GetPathRoot(Environment.SystemDi

我有一个方法,我想在同一个c#项目中的几乎所有类中使用


在项目的其他类中重用此方法的方法是什么?

如果要在所有类中使用此方法,请将其设置为
静态

您可以使用一个
static
LogHelper
类来更好地组织它,例如:

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)

调用它,您可以创建一个静态类并将此函数放入该类中

public static MyStaticClass
{
    public static void Log(String line)
    {
        // your code
    }
}
现在你可以叫它别处了。(不需要实例化,因为它是一个静态类)


您可以在statis类中使用
拉伸方法

字符串扩展的示例

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

link:

为什么不将log4net用于其他日志工具,而不是自己管理?我想用面向方面编程的链接发布答案,使用PostSharp用于某些IoC容器拦截器的编译时方面,用于动态方面。但他似乎只需要一个
静态
关键字…@IlyaIvanov是的,虽然IOC容器非常有用,但在这种情况下,它将是一把大锤。
MyStaticClass.Log("somestring");
public static class MyExtensions
    {
        public static int YourMethod(this String str)
        {
        }
    }