簡體   English   中英

內部帶有靜態實例的類

[英]Class with static instance inside

public class MyClass
{
    // private fields


    //////////////////////////////////////////////////////////////////////////
    public MyClass(string param1, string param2)
    {
        // do some stuff
    }

    private static object syncRoot = new Object();
    private static volatile MyClass instance = null;

    public static MyClass  Log
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new MyClass();
                }
            }

            return instance;
        }
    }

    private MyClass()
    {
        // do some stuff
    }

    public void myFunction(string txt, uint flags)
    {
         // do some stuff
    }
}

這是我的課,我用這種方式

    MyClass.Log.myFunction("some string", flags);

但是當我在其他類函數中使用此類時,經常會得到MyClass為null或MyClass.Log為null的錯誤。

我做錯了什么?

除了這里的問題是我得到的錯誤:

 System.NullReferenceException: Object reference not set to an instance of an object.
   at MyNamespace.MyClass..ctor()
   at MyNamespace.MyClass.get_Log()

您顯示的代碼看起來不錯。
MyClass不能為null因為它是一個類。 Log也不應該為null ,您的單例實現看起來不錯。

我的猜測是問題在於您正在使用MyClass的無參數構造函數。 我猜想myFunction以某種方式使用僅在采用兩個參數的構造函數中初始化的東西。

實際上,根據您的堆棧跟蹤,問題出在無參數構造函數內部。 我想您正在嘗試在其中登錄某些內容,例如: instance.Log(...); 那是行不通的,因為那時instance仍然為null 您應該只使用Log(...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM