我什么时候应该写静态方法? [英] When should I write Static Methods?

查看:161
本文介绍了我什么时候应该写静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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");



对于静态字段,正在创造singelton对象他们的最好用?

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

推荐答案

它给人的意图有更好的了解,当你使用一个静态的工厂 - 它也可以让你有采取不同的工厂相同的参数类型,但具有不同的意义。例如,想象一下,如果有位图LoadFromResource(字符串) - 它不可能有两个构造函数,这两个字符串了。

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.

修改 :从在评论stevemegson

EDIT: From stevemegson in the comments

一个静态的工厂也可以返回空值,并且可以更容易地返回实例,它从缓存中了。我的许多类都有一个静态FromId(INT)从一个主键得到一个例子,如果我们有一个返回一个现有的缓存实例。

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.

这篇关于我什么时候应该写静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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