13

非静的クラスの静的メソッドを次のように使用できないという事実を除いて、静的メソッドで非静的クラスを使用すること、同じ静的メソッドで静的クラスを使用することの一般的な利点(または欠点)は何ですか?拡張メソッド。

例えば:

class NonStaticClass
{
    public static string GetData()
    {
        return "This was invoked from a non-static class.";
    }
}

これに対して:

static class StaticClass
{
    public static string GetData()
    {
        return "This was invoked from a static class.";
    }
}

ある方法を別の方法よりも使用することのパフォーマンス/メモリへの影響は何ですか?

注:クラスをインスタンス化する必要がないとします。私のユースケースシナリオは、次のようなものに限定されています。

Console.WriteLine(NonStaticClass.GetData());
Console.WriteLine(StaticClass.GetData());
4

4 に答える 4

16

The main benefit is that if you make the class static, the compiler will make sure that your class will only have static members.

So anyone reading the code, will instantly see the class can't be instantiated, and there is no interaction to be considered with any instances of the class. Because there can't be any.

At the clr level, there is no notion of static. A static class is both abstract and sealed, which effectively prevents inheritance and instantiation.

As for performance, I don't see any possiblities for compiler or runtime to optimize one over the other.

In this example, I would focus on expressing your intent as clear as possible to the readers. You can always optimize later.

于 2012-04-05T18:15:27.633 に答える
3

いくつかの特殊性/制限があります:

  • 静的クラスをインスタンス化することはできません
  • 静的クラスを継承することはできません

So if you suppose such a behavior for you class (e.g. helper/util or extension methods container), if you want to limit it's usage - make it static.

于 2012-04-05T18:14:21.347 に答える
3

There are no benefits or drawbacks. It's just architectual decision.

Use static only classes in cases of providing a function set or function libriary. As you can not instantiate it, but you can use it like.

MyMathLibrary.Plot(...)

This types are usually imply state less behavior. I repeat, usually.

Use simple classes with static members when you have "normal" type but need somehow a stateless method, like for example:

public class MyType
{
    .... //some members 

    public static MyType ReadFromXml(XmlReader reader) {}
    public static void SaveToXml(MyType mt) {}
}

There is no a silver bullet, it's just a matter of architect choice.

于 2012-04-05T18:19:18.983 に答える
2

Performance implications: basically none.

You can create an instance of NonStaticClass, but since it has no non-static overriden methods it's pretty much as useful as saying object obj = new object(), which is to say it's useful for maybe locking and that's about it. Making the class static prevent someone from new-ing it, but it's not like that does any real harm.

It's more of a self documenting way of saying there's no reason to create an instance of the class.

于 2012-04-05T18:14:38.830 に答える