为什么选择静态类而不是单例实现? [英] Why choose a static class over a singleton implementation?

查看:21
本文介绍了为什么选择静态类而不是单例实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静态对比.单例问题之前在 SO 中已经讨论过很多次了.
然而,所有的答案都指出了单例的许多优点.
我的问题是 - 静态类与单例相比有什么优势?为什么不每次都简单地选择一个单身人士?

The Static Vs. Singleton question has been discussed before many times in SO.
However, all the answers pointed out the many advantages of a singleton.
My question is - what are the advantages of a static class over a singleton? Why not simply choose a singleton every time?

推荐答案

静态类是您盒子中的技术工具 - 基本上是一种语言功能.

Static class is a technical tool in your box - basically a language feature.

Singleton 是一种架构概念.

Singleton is an architectural concept.

您可以使用静态类作为实现单例概念的一种方式.或者您可以使用其他方法.

You may use a static class as a means to implement the singleton concept. Or you may use some other approach.

如果您不小心,在 C# 中使用静态类有两个潜在危险.

With static classes in C# there are two potential dangers if you're not careful.

  • 在应用程序生命周期结束之前不会释放所请求的资源
  • 静态变量的值在应用程序中共享.对 ASP.NET 应用程序尤其不利,因为这些值将在驻留在特定应用程序域中的站点的所有用户之间共享.

这篇关于为什么选择静态类而不是单例实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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