我们什么时候应该使我们的方法静态化? [英] When should we make our methods static ?

查看:82
本文介绍了我们什么时候应该使我们的方法静态化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候应该由具有静态操作的类来实现某些事情,以及何时由同一类中的一个或多个对象来实现?

when something should be implemented by a class with static operations and when by one or more objects from the same class

推荐答案

以下是一堆事实关于静态方法.

静态方法不能在接口中,这可能会很大.

它们也不能是抽象的或虚拟的.

静态类只能具有静态方法.

尽管我发现很难测量差异,但是静态方法更快.

静态构造函数在常规构造函数之前被调用,这可能非常有用.

所有扩展方法都是静态的.它们非常好用,因为它们使您可以将方法添加到您几乎无法控制的类中.特别是,您可以将它们添加到通常根本没有方法的枚举中.请注意,您可以对类本身执行此操作,而无需继承.

它们用于创建依赖项属性. DependencyProperty.Register是一个不错的选择.

我的建议如下.当上述考虑合理时,您就可以开始使用静态方法了.在此之前,可能还有其他更紧迫的问题.

附:对我来说,更有趣的问题是如何才能最好地利用静态变量和集合,但这不是要问的问题.
The following are a bunch of the facts about static methods.

Static methods cannot be in interfaces, which can be a big deal.

They also cannot be abstract or virtual.

A static Class can only have static methods.

Static methods are faster though I have found the difference hard to measure.

Static constructors are called before regular constructors, which can be quite useful.

All extension Methods are static . They are very nice in that they let you add methods to classes that you have little control over. In particular you can add them to an enum which normally gets no methods at all. Note that you can do this to the class itself, without inheritance.

They are used in the creation of Dependency properties. DependencyProperty.Register is a good one.

My advice is as follows. When the above considerations make sense you are ready to start using static methods. Until then there are probably other more pressing issues.

Ps: To me the more interesting question is how one can best leverage static variables and collections, but that was not the question asked.


在不希望直接调用方法而无需调用方法的情况下使用static关键字使用该类的实例,

关键字static用于使字段&属于类而不是其实例的方法

例子

use static keyword where u want to call a method directly without using the instance of the class,

the keyword static is used to make fields & methods which belong to the class rather than to its instance

example

class B
{
static void fun()
{
System.out.println("Hello");
}
public static void main(String args [])
{
fun();
}
}



谢谢&问候
基数:rose:



Thanks & Regards
Radix :rose:


好吧,任何您可能想要在没有方便对象且没有状态的对象上调用的方法都应该是静态的.如果它可以是静态的,则考虑使其变为静态.
Well, any method that you may want to call where you don''t have an object handy, and which has no state, should be static. If it can be static, then consider making it static.


这篇关于我们什么时候应该使我们的方法静态化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆