何时在实例类上使用静态类的准则? [英] Guidelines for when to use Static class over instance class?

查看:80
本文介绍了何时在实例类上使用静态类的准则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
何时在C#中使用静态类

Possible Duplicate:
When to Use Static Classes in C#

有人可以提供有关创建时间的指南,标准检查点 静态类以及何时创建实例类.

Can someone please provide guidelines , standard checkpoints on when to create static class and when to create instance class.

基本上,我在编写代码时看到很多次,而使用静态类和方法可以完成相同的事情,这让我感到困惑.

Basically many a times I see while writing a code that the same thing could have been done using static class and methods and i get confused with many things.

到目前为止,我知道以下检查要点:

So far i know below check points :

  1. 如果所考虑的对象在整个应用程序中只能存在一次,那么它将属于静态"

  1. If object under the consideration can exists only once in entire application then it would come under "static"

如果方法内部不使用任何字段变量,则它可以是静态方法.

If a method does not use any field variable inside it then it can be static method.

推荐答案

在我看来,最好的区分因素是状态.

To my mind the best differentiator is state.

如果您的类没有状态,而只是一系列相关的方法,当给定输入时,它们将为您提供输出,那么您就很适合使用静态类.

If your class has no state and is just a series of related methods that, when given an input, will give you an output then you have an excellent candidate for a static class.

如果将为您的班级提供输入然后进行存储,或者希望以其他方式保持班级的当前状态,则您有一个普通班级.

If your class will be given input and then store it or in some other way will be expected to maintain its current state then you have a regular class.

此外,如果您的类要声明为abstract或要从另一个类继承行为或从接口实现行为,那么您将远离静态类并拥有一个普通的类.

Furthermore if your class is going to be declared abstract or is going to inherit behaviours from another class or implement behaviours from an interface, then you're moving away from a static class and have a normal class.

简而言之:

  • 如果它是一袋方法没有状态
  • 它不是抽象的,继承或实现接口的
  • If it's a bag of methods or has no state
  • and it isn't abstract, inheriting or implementing an interface

那么您很有可能是静态类:)

Then you have a good chance it is a static class :)

我希望能帮上忙.

NB(根据下面的敏锐注释)状态是指存储一些数据的类,这些数据表示对象的当前事务状态.也许是类级变量或属性.

NB (as per the astute comment below) state refers to the class storing some data that represents the current state-of-affairs for an object. Perhaps a class-level variable or a property.

这篇关于何时在实例类上使用静态类的准则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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