类 中没有字段的静态方法和非静态方法的区别

Differents in static methods and non static methods in classes without fields

曾经有人写道:

The space required for an instance depends only on the fields.

The methods require memory too but only one time per class. Like static fields. That memory is allocated when the class is loaded.

但是,如果 class 具有 5 种方法 无字段 在其他字段中获得多个实例,会发生什么classes(组合)。 他们需要更多内存吗?或者它会和静态方法一样吗?

我问这个问题也是因为它甚至在编译时得到了优化?

静态方法与静态 class 有什么不同吗?除了你需要每次创建 class 或传递它之外?

例如:

class Test1
{
    public void DoThis()
    {
        ...
    }

    public void DoThat()
    {
        ...
    }
}

class Test2
{
    public void DoSomething()
    {
        ...
    }

    private Test1 sample = new Test1();

}

class Test3
{
    public void DoSomethingElse()
    {
        ...
    }

    private Test1 sample = new Test1();

}

And so on...

“在幕后”,class 方法就像一个静态方法,class 实例作为第一个参数通过引用传递。

也就是说,除非您使用 virtual methds,否则“在幕后”将保存为实例成员。

也就是说,因为只要不覆盖方法,就没有理由浪费实例的 space。

因此,您的 class 实例的大小不会受到您添加到 class 的任何非虚拟方法的影响。

这个概念可以在编程语言之间改变。例如,在 JavaPython 中,class 方法默认是虚拟的。