簡體   English   中英

C#靜態方法和屬性:未將對象引用設置為對象的實例

[英]C# static methods & attributes: Object reference not set to an instance of an object

我正在使用靜態方法和屬性,當我調用靜態方法時,我得到一個NullReferenceException

樣本類:

internal class Utils
{
    private static Regex[] _allRegexes = { _regexCategory };
    private static Regex _regexCategory = new Regex(@"(?<name>c(ategory){0,1}):(?<value>([^""\s]+)|("".+""))\s*", RegexOptions.IgnoreCase);

    public static string ExtractKeyWords(string queryString)
    {
        if (string.IsNullOrWhiteSpace(queryString))
            return null;   

        _allRegexes[0];//here: _allRegexes[0]==null throw an exception
    }
}    

原因:

_allRegexes [0] == NULL

我無法弄清楚為什么會發生這種情況,我認為_allRegexes應該在我調用該方法時初始化。

任何人都可以解釋一下嗎?

靜態字段按聲明順序初始化。 這意味着初始化_allRegexes_regexCategorynull

類的靜態字段變量初始值設定項對應於以它們出現在類聲明中的文本順序執行的賦值序列。

(引自C#語言規范版本4.0 - 10.5.5.1靜態字段初始化)

這導致_allRegexes成為包含單個null元素的數組,即new Regex[]{null}

這意味着你可以通過把修復代碼_regexCategory之前_allRegexes在你的類。

它應該是

    private static Regex _regexCategory = new Regex(@"(?<name>c(ategory){0,1}):(?<value>([^""\s]+)|("".+""))\s*", RegexOptions.IgnoreCase);
    private static Regex[] _allRegexes = { _regexCategory };

在你的代碼中, IL會將_regexCategory加載到_allRegexes ,這是NULL因為IL從未initialized它。

initalizes當實例_regexCategory 新的關鍵字

此代碼無需NRE即可運行

internal class Utils
{
    private static Regex _regexCategory = new Regex(
        @"(?<name>c(ategory){0,1}):(?<value>([^""\s]+)|("".+""))\s*", 
        RegexOptions.IgnoreCase);
    private static Regex[] _allRegexes = { _regexCategory };


    public static string ExtractKeyWords(string queryString)
    {
        if (string.IsNullOrWhiteSpace(queryString))
            return null;

        //change it to your needs, I just made it compile
        return _allRegexes[0].Match(queryString).Value;
    }
}    

class Program
{
    static void Main(string[] args)
    {
        string result = Utils.ExtractKeyWords("foo");
    }
}

我認為問題在於參數初始化的順序。

暫無
暫無

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

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