如何实现在C#中的单? [英] How to implement a singleton in C#?

查看:146
本文介绍了如何实现在C#中的单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现在C#中的单件模式?我想把我的常量和它的一些基本功能,因为我在我的项目中使用这些无处不在。我希望让他们'全球',而不是需要手动绑定他们,我创建的每一个对象。

How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.

推荐答案

如果你只是存储一些全局值,并有不需要国家的一些方法,你并不需要单身。只要类及其属性/方法静态的。

If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.

public static class GlobalSomething
{
   public static int NumberOfSomething { get; set; }

   public static string MangleString( string someValue )
   {
   }
}

当你有一个正常的类状态,但你只想要其中的一个

辛格尔顿是最有用的。别人提供的链接应该是在探索Singleton模式是有用的。

Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.

这篇关于如何实现在C#中的单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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