什么时候应该在基类中声明静态方法?
什么时候应该在基类和受保护方法中使用静态方法? (可以使用 base.MethodName 从派生类调用)
When should you use static methods in base class and protected methods? (which can be called from the derived class using base.MethodName)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅当您的方法不依赖于对象的状态时才应使用静态
当您只希望后代从基类调用方法时受保护。
Base.Method 一般在重写方法时使用
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 意味着您允许派生类访问基方法。
静态意味着方法不需要访问实例的状态。它们通常被称为类方法,而不是实例方法。
base 关键字仅在覆盖基类中的成员时才有用(此时基成员通常被标记为虚拟)。这允许您在派生类中重载基成员时引用它。
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.