C# 静态与非静态方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1184701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Static vs. non-static method
提问by Elad
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?
即使有一些性能或内存增益,编译器不会将其作为编译时的简单优化吗?
Edit:编辑:我正在寻找的是将方法声明为静态的好处。一世know知道这是常见的做法。我想了解它背后的逻辑。
当然,这个方法只是为了阐明我的意图的一个例子。
采纳答案by jerryjvl
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.
请注意,编译器甚至不太可能代表您进行更改,因为它更改了方法的签名。结果,一些精心设计的反射(如果您正在使用)可能会停止工作,并且编译器真的无法判断是否是这种情况。
回答by ufukgun
this method should be static because it is not related to your class or member of classes. it just works with the inputs to this function.
此方法应该是静态的,因为它与您的类或类的成员无关。它只适用于这个函数的输入。
maybe you may need to call it without creating that class. so if it is static it is ok but if it is not, you cant call it without any instance of that class.
也许您可能需要在不创建该类的情况下调用它。因此,如果它是静态的,则可以,但如果不是,则不能在没有该类的任何实例的情况下调用它。
Advantages of a static method:
静态方法的优点:
There's no need to create an object first. The method is available immediately.
无需先创建对象。该方法立即可用。
It's a good when you have generic functionality that does not depend on the state of a particular object. For example, look at the Arrays class or the Collections class from java.util.
当您拥有不依赖于特定对象状态的通用功能时,这是很好的。例如,查看 java.util 中的 Arrays 类或 Collections 类。
Static methods can be good for factories. Pass your requirements as parameters, get a brand new object back. Not a constructor in sight.
静态方法对工厂很有用。将您的要求作为参数传递,得到一个全新的对象。看不到构造函数。
Disadvantages of a static method:
静态方法的缺点:
You don't have an object instance, so you only have access to static members and your own local variables. If you want an instance, you probably have to create it yourself.
您没有对象实例,因此您只能访问静态成员和您自己的局部变量。如果你想要一个实例,你可能必须自己创建它。
You can create subclasses, but a static method can't be abstract, so it's harder to decouple your implementation from a caller.
您可以创建子类,但静态方法不能是抽象的,因此很难将您的实现与调用者分离。
(ps: i dont think compiler will optimize if it is going to be static or not.. but not sure)
(ps:我不认为编译器会优化它是否是静态的......但不确定)
回答by jason
As defined, power
is stateless and has no side effects on any enclosing class so it should be declared static
.
正如定义的那样,power
是无状态的,对任何封闭类都没有副作用,因此应该声明它static
。
This articlefrom MSDN goes into some of the performance differences of non-static versus static. The call is about four times faster than instantiating and calling, but it really only matters in a tight loop that is a performance bottleneck.
MSDN 上的这篇文章探讨了非静态与静态的一些性能差异。调用大约比实例化和调用快四倍,但它只在作为性能瓶颈的紧密循环中真正重要。
回答by Cody C
To me an easy question to decide is "Should I have to instantiate this object just to call this function". In the case of your function, I would say the answer is no, so it should be static. This method does not seem to be related to your object so again, I vote static.
对我来说,一个容易决定的问题是“我是否必须实例化这个对象来调用这个函数”。对于你的函数,我会说答案是否定的,所以它应该是静态的。这种方法似乎与您的对象无关,所以我再次投票给静态。
回答by Thomas Levesque
There should be a slight performance improvement if you declare the method static, because the compiler will emit a call
IL instruction instead of callvirt
.
如果您将方法声明为静态,应该会有轻微的性能改进,因为编译器将发出call
IL 指令而不是callvirt
.
But like the others said, it should be static anyway, since it is not related to a specific instance
但就像其他人说的,它无论如何都应该是静态的,因为它与特定实例无关
回答by Adam Ralph
I believe the compiler will not optimise this into a static method. There is a performance gain since the pointer will not have to be checked to see if it is null at runtime. Have a look at the FXCop rulefor reference.
我相信编译器不会将其优化为静态方法。由于在运行时不必检查指针以查看它是否为空,因此性能有所提高。查看FXCop 规则以供参考。
回答by jcoder
The compiler will likely consider inlining this when it "JITs" the code as it's so short and if it does so then will likely be able to optimise out any reference to the unused this parameter. But you can't rely on any of that.
编译器可能会在“JIT”代码时考虑内联它,因为它很短,如果这样做,那么可能能够优化对未使用的 this 参数的任何引用。但你不能依赖其中任何一个。
You still have to make an object to call it on unless you make it static which has a much bigger overhead anyway if you don't need one for other reasons.
您仍然必须创建一个对象来调用它,除非您将其设为静态,否则如果您出于其他原因不需要它,那么它的开销会更大。
回答by Pritom Nandy
i hope we need to define the difference between static and non-static method. Here i am posting few easy lines of code to visualize the conceptual difference.
我希望我们需要定义静态和非静态方法之间的区别。在这里,我发布了几行简单的代码来可视化概念差异。
public class StaticVsNonStatic
{
public string NonStaticMethod() //non-static
{
return "I am the Non-Static Method";
}
static public string StaticMethod() //static
{
return "I am Static Method";
}
}
Now lets create an aspx page try to access these 2 methods defined in the class.
现在让我们创建一个 aspx 页面,尝试访问类中定义的这 2 个方法。
public partial class StaticVsNonStatic_StaticVsNonWorkplace : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StaticVsNonStatic objStaticVsNonStatic = new StaticVsNonStatic();
lblDisplayNS.Text = objStaticVsNonStatic.NonStaticMethod(); //Non Static
lblDisplayS.Text = StaticVsNonStatic.StaticMethod(); //Static and called without object
}
}
Thanks and please post you comments.
谢谢,请发表评论。
Best Regards, Pritom Nandy [Bangladesh]
最好的问候, Pritom Nandy [孟加拉国]
回答by Manjunatha
Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
不访问实例数据或调用实例方法的成员可以标记为静态(在 Visual Basic 中为共享)。将方法标记为静态后,编译器将向这些成员发出非虚拟调用站点。发出非虚拟调用站点将阻止在运行时对每个调用进行检查,以确保当前对象指针为非空。这可以为性能敏感的代码实现可测量的性能增益。在某些情况下,无法访问当前对象实例表示正确性问题。
回答by Boann
Do you see any benefit from changing the method signature into static?
您看到将方法签名更改为静态有什么好处吗?
Three benefits:
三大好处:
Making stateless methods static helps document and clarify their purpose. Otherwise, one is inclined to worry just what mysterious state does the method depend upon?
The static method can be called from other static code, so is potentially more useful.
Static method calls have a smidgin less runtime overhead than instance ones. The compiler can't do that transform automatically -- one reason why is because it would affect use of null. Calling the method on a null reference is required to fail with a NullReferenceException, even if there is no instance state used within the method.
将无状态方法设为静态有助于记录和阐明其目的。否则,人们往往会担心该方法依赖于什么神秘状态?
静态方法可以从其他静态代码中调用,因此可能更有用。
静态方法调用的运行时开销比实例调用少一点。编译器不能自动进行这种转换——原因之一是它会影响 null 的使用。即使在方法中没有使用实例状态,在空引用上调用方法也会失败并返回 NullReferenceException。