将私有方法声明为静态有什么好处以及何时使用它?
我为什么要使用:
private static string GetSomething()
{
return "Something";
}
代替:
private string GetSomething()
{
return "Something";
}
您可以声明一个私有静态方法,作为向其他开发人员发出此方法不使用实例数据的信号的一种方式。
这是MSDN所说的
对静态方法的调用会生成 Microsoft 中间语言 (MSIL) 的调用指令,而对实例方法的调用会生成 callvirt 指令,该指令还会检查空对象引用。但是,大多数时候两者之间的性能差异并不显着。
简而言之,这意味着会有一些性能提升。
考虑下面的简单设计,其中私有静态具有重要意义。
您想要隐藏一些数据(抽象)并希望在类的静态和非静态函数中使用该数据:
考虑下面的例子:
public class test
{
private static int funcValue()
{
return 200;
}
public static void someStaticFunc()
{
int x = funcValue();
}
public void anotherNonStaticFunc()
{
int y = funcValue();
}
}
调用:
test t = new test();
test.someStaticFunc();//static
t.anotherNonStaticFunc();//non-static
在上面的示例中,如果您不声明funcValue
为静态,则不能在静态函数中调用它,someStaticFunc
并且您希望funcValue
是私有的(抽象)。