简体   繁体   中英

what the point of declaring a static method in a non-static class?

The way I understand it, having a member variable declared as static in a no-static class causes that member variable to be unique no-matter the number of instances of that class.

Now, what happen to a static method declared in non-static class? And ( Most importantly ), what the point of declaring a static method in a non-static class?

Thanks for helping

If the method has something to do with the type but not the instance then it can be static.

DateTime.Parse and Int32.Parse are examples.

这对于创建不是任何对象的成员但需要访问对象内部以对其进行初始化的工厂方法很有用。

You need static methods in non-static classes fe for the factory pattern (if the class is a factory for itself, as pointed out by Jaco Pretorius):

  MyClass newInstance = MyClass.Create();

Or if you want to create helper methods. Fe you could write an FTP-Class which is fully working, with Connect() , SendCommand() , ReceiveAnswer() , Disconnect() etc., but you want to allow the user to easily upload one file, without the need to implement the whole procedure:

  MyFTPClass.UploadFile("username", "password", "pathToFile");

Class method which works only with its parameters, doesn't call any instance methods and doesn't work with any instance members, may be declared as static. Actually, it should be declared as static, for better performance, since static method doesn't require "this" pointer.

Consider small function which belongs to class, makes some calculations with its parameters and returns calculated value. This function should be static.

It would be impossible to implement the Singleton pattern without being able to declare a static method (and private member variable) on a non-static class.

See Singleton

For example you have a class for example Bank_Account in which you want to calculate the number of object created for that class.
So, you have one static field say count . Then when you initialize any object of class Bank_Account then you need to increment the field which stores the number of objects created for this class, the method incrementing this static variable is static as it is same for all the objects created for this class.

As ck said, it can be methods that has something to do with the type. It is important to remember that this will be a utility function, that will not be able to access any member variables in the type/class, since it may be called directly without having any instance of the class. If you try to define a static method that accesses a member variable (or non-static method), you will actually get a compiler error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM