使用静态构造函数在 C# 中创建单例 [英] Using Static constructors to create a singleton in C#

查看:67
本文介绍了使用静态构造函数在 C# 中创建单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在查看有关在 c# 中创建静态构造函数的文章:

I've been looking at the article on creating static constructors in c# here:

http://csharpindepth.com/Articles/General/Singleton.aspx

现在,他没有提到的一个选项是使用简单的静态构造函数.做类似下面的事情有什么问题吗?如果它有效,恕我直言,它似乎比他复杂的解决方案更简单.

Now, one option he doesn't mention is using a simple static constructor. Is there any issue with doing something like the below? If it works, it seems simpler than his complicated solutions IMHO.

public static class ServiceFactory
{
  static ServiceFactory()
  {
    container = new Foo();
  }
  static Foo container;

  public static Instance {
    get {
    return container;
    }
  }
}

我问的原因是我正在进行代码审查,如果没问题的话,我想保持原样.

The reason i ask is i'm doing a code review and want to leave it as-is if it's fine.

推荐答案

您的代码不是构建单例.它正在创建一个 Foo 的实例,并且想必其他任何人也可以 - 这意味着它不是一个单例.

Your code isn't building a singleton. It's creating an instance of Foo, and presumably anyone else could too - which means it isn't a singleton.

您已经创建了一个由 ServiceFactory 中的静态变量引用的实例,但这不是一回事.

You've created a single instance which is referred to by a static variable in ServiceFactory, but that's not the same thing.

除非你有一些你限制的类,以至于它只能有一个实例,否则你没有单例.你可能有一个工厂模式、一个缓存等等——但你没有一个单例.

Unless you have some class which you've restricted so that there can only ever be one instance of it, you don't have a singleton. You may have a factory pattern, a cache, whatever - but you don't have a singleton.

现在你得到的就相当于这个:

Now what you've got is equivalent to this:

static Foo container = new Foo();
static ServiceFactory()
{
}

...我不知道为什么你认为你的版本比上面的更简单.如果您确实想要真正创建一个单例,那么您将需要一个私有构造函数,用于您试图将其变成单例的任何类.到那时,你基本上已经得到了我的第四个例子,所以我再次不确定你认为你在哪里让事情变得更简单.

... and I'm not sure why you think your version is simpler than the above. If you do want to actually create a singleton, you're going to need a private constructor for whatever class you're trying to turn into a singleton. At that point, you've basically got my fourth example, so again I'm not sure where you think you're making things simpler.

当然,您可能根本不需要静态构造函数 - 这取决于您需要的时间精确度.(阅读我关于beforefieldinit 的文章,了解更多详情,以及我的 博客文章关于 CLR v4 的变化.)

Of course, you may not need a static constructor at all - it depends on how precise you need the timing to be. (Read my article on beforefieldinit for more details, along with my blog post about the CLR v4 changes.)

这篇关于使用静态构造函数在 C# 中创建单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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