7

一般的な質問があります...静的クラスまたは静的メソッドをいつ使用する必要がありますか?..静的メソッドはインスタンス化せずに呼び出すことができるという考えを知っています...そして静的クラスは静的メソッドにのみ使用する必要がありますか?...しかし、パフォーマンスに関する懸念もありますか...そして、インスタンスメソッドやクラスよりもいつそれらを優先する必要がありますか?

4

4 に答える 4

6

次の2つのリンクは、あなたが探しているものに対する明確な答えを提供すると思います。それらを見てください:

静的クラスの場合:

C#で静的クラスを使用する場合

静的メソッドの場合:

静的メソッドを使用するのが適切なのはいつですか?Jon Skeet [教祖]がこれに答えました:o))

于 2010-07-14T23:23:37.300 に答える
4

One thing to keep in mind is the testing implications of static methods. A static method "seals" a lot of seams. Seams are where you can change behavior without changing your production code; examples are subclassing, or linking to a testing library. Since static methods are resolved at compile time and aren't dynamically bound you can't throw in a testing object and change the way a static method behaves. Testing that class is going to be a drag.

For things like mathematical functions you can be pretty sure a static method will be ok, but you almost certainly wouldn't want a static method that connects to a database. Think about how you'd test code that uses a static method you're thinking of making.

Here's a good link from the google testing blog:Static Methods are Death to Testability

于 2010-07-15T01:07:17.723 に答える
1

一般的な経験則では、効用関数は静的である必要があると思います。典型的な例は、どのoop言語でも、Mathクラスにsqrt()のような静的メソッドが含まれる方法です。これは、別のMathオブジェクトのようなものは実際には必要ないためです。

静的クラスに関しては、通常はセッション情報のような状態の形式を保持するクラスを考える必要があります。これは、アプリケーションを通過する正確なパスに関係なく必要であり、通常は1つだけ必要です。(ブラウザを考えてみてください。おそらく、クラスのようなcookie-jarを常に1つだけ保持します)

静的変数は、グローバル変数のそれほど邪悪な双子ではありません(値は保持しますが、スコープは関数に限定されます)。これは通常、何らかの形式の状態(データのキャッシュなど)を保持するか、必要なものを列挙するのに役立ちます。一意ですが、その番号付けは関数またはアプリケーションの範囲外ではそれほど重要ではありません(たとえば、独自のdebug( "..")またはprofile()関数からの番号付けのデバッグまたはプロファイリングの叫び)

基本的に、「正しい」OOPのような方法でモンスターを作成できると確信している場合にのみ、これらのいずれかを使用してください。

于 2010-07-15T00:08:36.117 に答える
0

As I understand it that's when there's no sense to create an object of a class to invoke an action or that class is common within the application. For example, in C#, Console class is sealed (so you can't create an object and inherit it, and there's really no sense to do it). But professionals will explain you better, however.

于 2010-07-15T00:12:49.747 に答える