C# 静态方法和属性 : Object reference not set to an instance of an object

标签 c# .net static-methods

我正在使用静态方法和属性,当我调用静态方法时,我得到一个 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

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.

(引自 C# Language Specification Version 4.0 - 10.5.5.1 Static field initialization)

这导致 _allRegexes 成为包含单个 null 元素的数组,即 new Regex[]{null}

这意味着您可以通过将 _regexCategory 放在类中的 _allRegexes 之前来修复您的代码。

关于C# 静态方法和属性 : Object reference not set to an instance of an object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12025367/

相关文章:

java - 静态方法重写

c# - 使用 SQLConnection 连接到 SQL CE 数据库

c# - 将参数发送到操作方法

.NET TAPI 接口(interface)

c# - 添加对 netstandard 2.0 的引用的问题

java - 我在理解 Java 多态性时遇到了一些麻烦

.net - Fluent Interfaces - 正在创建的对象的数量

c# - 为类中的 int 元素覆盖 ToString()

c# - 访问 ASP.NET 表中的控件

c# - 获取类型的默认值