将方法定义为静态更好吗?

Edw*_*vey 1 c# static static-methods

是否存在内存或性能差异来静态定义和使用方法而不是使用实例化类中的方法?当方法不是静态时,方法本身是否会使用类的每个实例占用内存?

也许在静态方法中声明的任何变量都是非线程安全的?

/// <summary>
/// A class using instance methods (non-static)
/// </summary>
public class Junk
{
    public int x {get; protected set;}
    public Junk(int x = 0)
    {
        this.x = x;
    }
    public void Increment()
    {
        this.x++;
    }
}
Run Code Online (Sandbox Code Playgroud)

/// <summary>
/// A class using static methods
/// </summary>
public class Junk
{
    public int x {get; protected set;}
    public Junk(int x = 0)
    {
        this.x = x;
    }
    public static void Increment(Junk thisJunk)
    {
        thisJunk.x++;
    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 7

没有区别.如您的示例所示,实例方法在逻辑上只不过是一个静态方法,其中第一个参数名为"this".唯一的区别是在实例方法中自动检查"this"是否为null.它不是静态方法.

现在,方法确实会导致性能成本,因为实际调用的方法必须在运行时计算,而不是在编译时计算.这可以为程序的运行时添加几纳秒,并且还排除了某些优化,例如内联.

至于线程安全:变量是否安全使用是整个程序的属性,而不是方法是否是静态的属性.