简体   繁体   中英

When should static methods be declared in the base class?

When should you use static methods in base class and protected methods? (which can be called from the derived class using base.MethodName)

Statics should only be used when your method doesn't depends on the state of the object
Protected when you want only the descendants to call methods from base.

Base.Method in general is used when overriding methods

Protected and static are not exclusive.

protected means you allow derived classes to access the base method.

static means the methods does not need to access the state of the instances. The are often called class methods as opposed to instance methods.

The base keyword is only useful when overriding a member from the base class (the base member is often marked as virtual then). This allows you to reference the base member in case you have overloaded it in the derived class.

One benefit of a static method is that only one copy of the code remains in memory. This can be particularly useful if you have large collections of objects with many methods. in other words, It can reduce your memory footprint. You might also find it easier or more intuitive to control protected blocks of code when acting upon shared data in a multithreaded architecture. However, you may find it syntactically unpleasant to pass a casted (base class) instance of the object into one of it's base class static methods, and some developers may be confused by this coding style, so commenting such code is always a good idea.

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