[英]C# static methods & attributes: Object reference not set to an instance of an object
I'm using static methods and attributes, when I call a static method, I get a NullReferenceException
. 我正在使用静态方法和属性,当我调用静态方法时,我得到一个NullReferenceException
。
sample class: 样本类:
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
}
}
cause: 原因:
_allRegexes[0]==null _allRegexes [0] == NULL
I can't figure it out why this happens, I think _allRegexes
should be initialized when I call that method. 我无法弄清楚为什么会发生这种情况,我认为_allRegexes
应该在我调用该方法时初始化。
Can anybody explain it? 任何人都可以解释一下吗?
Static fields get initialized in declaration order. 静态字段按声明顺序初始化。 This means _regexCategory
is null
when you initialize _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. 类的静态字段变量初始值设定项对应于以它们出现在类声明中的文本顺序执行的赋值序列。
(Quoted from C# Language Specification Version 4.0 - 10.5.5.1 Static field initialization) (引自C#语言规范版本4.0 - 10.5.5.1静态字段初始化)
This leads to _allRegexes
becoming an array that contains a single null
element, ie new Regex[]{null}
. 这导致_allRegexes
成为包含单个null
元素的数组,即new Regex[]{null}
。
This means you can fix your code by putting _regexCategory
before _allRegexes
in your class. 这意味着你可以通过把修复代码_regexCategory
之前_allRegexes
在你的类。
It should be 它应该是
private static Regex _regexCategory = new Regex(@"(?<name>c(ategory){0,1}):(?<value>([^""\s]+)|("".+""))\s*", RegexOptions.IgnoreCase);
private static Regex[] _allRegexes = { _regexCategory };
In your code the IL
will load _regexCategory
into _allRegexes
which is NULL
because the IL had never initialized
it.. 在你的代码中, IL
会将_regexCategory
加载到_allRegexes
,这是NULL
因为IL从未initialized
它。
It initalizes
when you instantiate _regexCategory
with new keyword 它initalizes
当实例_regexCategory
新的关键字
This code works without NRE 此代码无需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");
}
}
I believe the problem is in the order in which parameters are getting initialized. 我认为问题在于参数初始化的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.