When should I write Static Methods?

后端 未结 8 830
梦如初夏
梦如初夏 2021-01-04 02:31

So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and field

8条回答
  •  南笙
    南笙 (楼主)
    2021-01-04 02:54

    Use a static method when the method does not belong to a specific object.

    For example, if you look at the Math class in .NET framework, you will see that all methods are static. Why? Because there is no reason to must create an object to use the methods. Why would you want to create an object of the Math class, when all you want is the absolute value of something? No, there is no reason to do this, and therefore, the method is static.

    So when you design a class, ask yourself:

    Does this method belong to an object, or the class itself?

    A method belongs to an object, if it modifies the state of the object. If the method does not modify a specific object, it can most likely be static.

    Another example, suppose that you want to know how many objects of a class that is created (don't ask me why...). For this task, you could create a static method GetNumberOfObjects() (and you obviously need a static field, and some code in the constructor too). Why would i have it static, you might ask. Well, answer the above question, and you will see. The method does not belong to any specific object. Additionally, it does not modify any object.

    I hope this makes sense.

提交回复
热议问题