这些方法为单例创建静态实例有什么区别? [英] What's the difference in these ways of creating the static instance for a singleton?

查看:159
本文介绍了这些方法为单例创建静态实例有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到一个错误,只有当库被构建为发布版本而不是调试版本时才会显示出来。该库是一个.NET DLL与COM包装和我使用CoCreateInstance从一个非托管的c ++应用程序中的dll创建一个类。当我终于跟踪错误,它是由访问一个单例对象造成的。我有单例实例如此声明:

I have had a bug recently that only manifested itself when the library was built as a release build rather than a debug build. The library is a .NET dll with a COM wrapper and I am using CoCreateInstance to create a class from the dll in an unmanaged c++ app. When I finally tracked the bug down it was caused by accessing a singleton object. I had the singleton instance declared like so:

private static readonly MyObjectType s_instance = new MyObjectType;

,然后使用:

public static MyObjectType Instance 
    { 
        get 
        {                               
            return s_instance; 
        } 
    } 

这是失败。将其更改为:

this was failing. Changing it to:

private static MyObjectType s_instance;

public static MyObjectType Instance 
    { 
        get 
        {               
            if (s_instance==null) 
            { 
                s_instance = new MyObjectType(); 
            } 
            return s_instance; 
        } 
    } 

修正了问题。任何想法为什么最初的用法没有工作,如果有任何缺点,以任何一种方式?

fixed the issue. Any ideas why the initial usage didn't work and if there are any downsides to doing it either way?

发布dll似乎完全可以从另一个管理应用程序使用。

The release dll seemed to be perfectly usable from another managed app.

推荐答案

尝试在静态构造函数中添加(空)静态构造函数或初始化

Try adding an (empty) static constructor, or initialize the singleton in a static constructor.

Jon Skeet对单身模式进行了全面讨论这里。我不知道为什么它失败,但在一个猜测,它可能与beforefieldinit标志有关。看到他的第四个例子,他添加了一个静态构造函数来调整这个标志。我不声称自己是beforefieldinit的专家,但这种症状似乎适合一些讨论的症状这里

Jon Skeet has a full discussion of singleton patterns here. I'm not sure why it failed, but at a guess it could relate to the "beforefieldinit" flag. See his 4th example, where he adds a static constructor to tweak this flag. I don't claim to be an expert on beforefieldinit, but this symptom seems to fit some of the symptoms discussed here.

这篇关于这些方法为单例创建静态实例有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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