问题描述
假设你有一些方法可以作出静态,非静态内部类。
例如:
Suppose you have some method that could be made static, inside a non-static class.
For example:
private double power(double a, double b)
{
return (Math.Pow(a, b));
}
你看到更改方法签名为静态任何好处?在上面的例子:
Do you see any benefit from changing the method signature into static? In the example above:
private static double power(double a, double b)
{
return (Math.Pow(a, b));
}
即使有一些性能或内存的增益,不会编译器做在编译时一个简单的优化?
修改什么我找的是通过声明的方法为静态的好处。我知道,这是常见的做法。我想了解它背后的逻辑。
当然,这种方法只是为了澄清我的意图的例子。
Even if there is some performance or memory gain, wouldn't the compiler do it as a simple optimization in compile time?
What I am looking for are the benefits by declaring the method as static. I know that this is the common practice. I would like to understand the logic behind it.
And of course, this method is just an example to clarify my intention.
推荐答案
请注意,这是极不可能的编译器甚至不允许代表您这种变化,因为它改变了方法的签名。其结果是,一些精心制作的反射(如果你使用任何)可能停止工作,并且编译器真的不能告诉如果是这种情况。
Note that it is highly unlikely the compiler is even allowed to make that change on your behalf since it changes the signature of the method. As a result, some carefully crafted reflection (if you were using any) could stop working, and the compiler really cannot tell if this is the case.
这篇关于静态与非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!