且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将方法声明为静态的增益是多少

更新时间:2023-11-13 18:23:52

每当您编写方法时,您都会在给定范围内完成合同。

Whenever you write a method, you fulfill a contract in a given scope. The narrower the scope is, the smaller the chance is that you write a bug.

当一个方法是静态的,你不能访问非静态成员;因此,您的范围更窄。因此,如果您不需要 并且永远不需要(即使在子类中) 非静态成员来履行您的合同,为什么允许访问这些字段到您的方法?在这种情况下声明方法 static 将允许编译器检查您不使用您不打算使用的成员。

When a method is static, you can't access non-static members; hence, your scope is narrower. So, if you don't need and will never need (even in subclasses) non-static members to fulfill your contract, why give access to these fields to your method? Declaring the method static in this case will let the compiler check that you don't use members that you do not intend to use.

而且,它将帮助阅读你的代码的人理解合同的性质。

And moreover, it will help people reading your code understand the nature of the contract.

这就是为什么声明一个方法

That's why it's considered good to declare a method static when it's actually implementing a static contract.

在某些情况下,你的方法只是一个相对于你的类的实例的东西,并且它的实现实际上不使用任何非静态字段或实例。在这种情况下,您不会标记方法 static

In some cases, your method only means something relative to an instance of your class, and it happens that its implementation doesn't actually use any non-static field or instance. In such cases, you would not mark the method static.

您不会使用 static 关键字:


  • 一个没有做任何事情的扩展钩子

  • 一个非常简单的默认行为意味着可以在子类中自定义。

  • 事件处理程序实现:事件处理程序,但不会使用事件处理程序实例的任何属性。