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