C# 我应该什么时候写静态方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/202560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:50:20  来源:igfitidea点击:

When should I write Static Methods?

c#oop

提问by Chris Smith

So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields.

所以我明白什么是静态方法或字段,我只是想知道什么时候使用它们。也就是说,在编写代码时,什么设计适合使用静态方法和字段。

One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example:

一种常见的模式是使用静态方法作为静态工厂,但这也可以通过重载构造函数轻松完成。正确的?例如:

var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg");

As for static fields, is creating singelton-objects their best use?

至于静态字段,创建单个对象是他们的最佳用途吗?

采纳答案by Lou Franco

It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string.

当您使用静态工厂时,它可以更好地了解意图——它还允许您拥有采用相同参数类型但具有不同含义的不同工厂。例如,想象一下如果 Bitmap 有 LoadFromResource(string) —— 不可能有两个都接受字符串的构造函数。

EDIT: From stevemegson in the comments

编辑:来自评论中的 stevemegson

A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one.

静态工厂也可以返回 null,并且可以更轻松地返回它从缓存中获取的实例。我的许多类都有一个静态 FromId(int) 来从主键获取一个实例,如果我们有一个,则返回一个现有的缓存实例。

回答by shoosh

Static methods are usually useful for operations that don't require any data from an instance of the class (from this) and can perform their intended purpose solely using their arguments.
A simple example of this would be a method Point::distance(Point a, Point b);that calculates the distance between two points and don't require an instance.

静态方法通常适用于不需要来自类的实例 (from this) 的任何数据并且可以仅使用它们的参数来执行其预期目的的操作。
一个简单的例子Point::distance(Point a, Point b);是计算两点之间的距离并且不需要实例的方法。

Static fields are useful among others for constants that don't change all that often and are used by all the instances of a class.

静态字段对于不经常更改并由类的所有实例使用的常量非常有用。

回答by JacquesB

I would say use static methods whenever you have functions which are independent of the state of the instance, ie. doesn't depend on any instance fields.

我会说只要你有独立于实例状态的函数,即使用静态方法。不依赖于任何实例字段。

The less non-local state that a method depends on, the easier it is to understand, so staticis a helpful signal to the reader of the code.

一个方法所依赖的非本地状态越少,就越容易理解,这static对代码的读者来说也是一个有用的信号。

回答by Corbin March

I keep it clear by remembering that instance methods work on/inside individual objects while static methods do something for the Class.

我通过记住实例方法在单个对象上/内部工作而静态方法为类做一些事情来保持清楚。

In the case of LoadFromFile(), you want a static method because you want a null reference if the load fails - the instance doesn't exist yet. If you implemented it as a constructor, you'd have to throw an Exception on failure.

在 LoadFromFile() 的情况下,您需要一个静态方法,因为如果加载失败,您需要一个空引用 - 实例尚不存在。如果您将它实现为构造函数,则必须在失败时抛出异常。

Other good uses for statics: Compare(obj a, obj b), Delete(obj a) for data objects (an object can't delete itself since its reference is still around), or static Classes for procedural code that honestly can't be modeled in an object.

静态的其他用途:Compare(obj a, obj b)、Delete(obj a) 用于数据对象(一个对象不能删除自己,因为它的引用仍然存在),或用于程序代码的静态类,老实说不能在对象中建模。

回答by Vincent Ramdhanie

You may use static methods when the client of the class do not have an instance of the class to work with. For instance the Singleton design pattern is used to ensure that only one instance of a class exist in the system. It requires that the constructors of the Singleton be private so that no instances can be created by the client.

当类的客户端没有要使用的类的实例时,您可以使用静态方法。例如,单例设计模式用于确保系统中只存在一个类的一个实例。它要求 Singleton 的构造函数是私有的,这样客户端就不能创建任何实例。

So if you cannot create an instance how do you access the instance methods of the class? By calling a static method that returns the Singleton instance of the class.

因此,如果您无法创建实例,您如何访问类的实例方法?通过调用返回类的 Singleton 实例的静态方法。

This is of course just one scenario but there are many others.

这当然只是一种情况,但还有许多其他情况。

回答by DJClayworth

Here are some examples of when you might want to use static methods:

以下是您可能想要使用静态方法的一些示例:

1) When the function doesn't make use of any member variables. You don't have to use a static method here, but it usually helps if you do.

1) 当函数不使用任何成员变量时。您不必在此处使用静态方法,但如果您这样做通常会有所帮助。

2) When using factory methods to create objects. They are particularly necessary if you don't know the type to be created in advance: e.g.

2) 使用工厂方法创建对象时。如果您事先不知道要创建的类型,它们尤其必要:例如

class AbstractClass {
    static createObject(int i) {
        if (i==1) {
           return new ConcreteClass1();
        } else if (i==2) {
           return new ConcreteClass2();
        }
     }
}

3) When you are controlling, or otherwise keeping track of, the number of instantiations of the class. The Singleton is the most used example of this.

3) 当您控制或以其他方式跟踪类的实例化数量时。Singleton 是最常用的例子。

4) When declaring constants.

4) 声明常量时。

5) Operations such as sorts or comparisons that operate on multiple objects of a class and are not tied to any particular instance.

5) 诸如排序或比较之类的操作,它们对一个类的多个对象进行操作,并且与任何特定实例无关。

6) When special handling has to be done before the first instantiation of an object.

6) 在对象的第一次实例化之前必须进行特殊处理时。

回答by David Grayson

You should use static methods whenever you have a function that does not depend on a particular object of that class.

只要有一个不依赖于该类的特定对象的函数,就应该使用静态方法。

There is no harm in adding the static keyword: it will not break any of the code that referred to it. So for example, the following code is valid whether or not you have the 'static' keyword:

添加 static 关键字没有坏处:它不会破坏任何引用它的代码。因此,例如,无论您是否有 'static' 关键字,以下代码都是有效的:

class Foo
{
    public Foo(){}
    public static void bar(){}  // valid with or without 'static'
    public void nonStatic(){ bar(); }
}

...
Foo a = new Foo();
a.bar();

So you should add 'static' to whatever methods you can.

因此,您应该将“静态”添加到您可以使用的任何方法中。

回答by iamCR

Use a static method when the method does not belong to a specific object.

当方法不属于特定对象时,使用静态方法。

For example, if you look at the Math class in .NET framework, you will see that all methods are static. Why? Because there is no reason to must create an object to use the methods. Why would you want to create an object of the Mathclass, when all you want is the absolute value of something? No, there is no reason to do this, and therefore, the method is static.

例如,如果您查看 .NET 框架中的 Math 类,您将看到所有方法都是静态的。为什么?因为没有理由必须创建一个对象才能使用这些方法。Math当您想要的只是某物的绝对值时,为什么要创建类的对象 ?不,没有理由这样做,因此,该方法是静态的。

So when you design a class, ask yourself:

所以当你设计一个类时,问问自己:

Does this method belong to an object, or the class itself?

这个方法属于一个对象,还是属于类本身?

A method belongs to an object, if it modifies the state of the object. If the method does not modify a specific object, it can most likely be static.

一个方法属于一个对象,如果它修改了对象的状态。如果该方法不修改特定对象,则它很可能是静态的。

Another example, suppose that you want to know how many objects of a class that is created (don't ask me why...). For this task, you could create a static method GetNumberOfObjects()(and you obviously need a static field, and some code in the constructor too). Why would i have it static, you might ask. Well, answer the above question, and you will see. The method does not belong to any specific object. Additionally, it does not modify any object.

另一个例子,假设您想知道创建了一个类的多少个对象(不要问我为什么...)。对于此任务,您可以创建一个静态方法GetNumberOfObjects()(显然您需要一个静态字段,以及构造函数中的一些代码)。你可能会问,为什么我要把它设为静态。好了,回答上面的问题,你就知道了。该方法不属于任何特定对象。此外,它不会修改任何对象。

I hope this makes sense.

我希望这是有道理的。