(C#) 为什么此代码不抛出 TypeInitializationException?
(C#) Why is this code not throwing a TypeInitializationException?
我正在 .NET CF 3.5 环境中开发 C# Winform 应用程序。
我了解到在下面的示例中出现了 TypeInitializationException。
static int [] ArrayB = new int [ArrayA.Length];
static int [] ArrayA = new int [] {1, 2, 3, 4};
这是因为在声明ArrayB 时ArrayA 为空。所以按照下图改就不会报错了。
static int [] ArrayA = new int [] {1, 2, 3, 4};
static int [] ArrayB = new int [ArrayA.Length];
那么为什么下面的例子没有抛出 TypeInitializationException?
static int [] ArrayB = new int [len];
static int len = 4;
ArrayB 在 len 之前声明。我认为应该发生错误,因为在声明 ArrayB 时 len 尚未初始化。
但是为什么没有出现错误呢?
即使它没有抛出异常,ArrayB 的长度仍然为零(int 的默认值)。这是某人的解释:"The cause of the unexpected value can be found in the C# Language Specification. This is the definitive documentation for C# syntax and usage. The document specifies that static fields can never be seen as uninitialised values. If they are accessed before a value has been applied, the default value for their data type is returned. For integer values, this is zero. The C# Language Specification also tells us that when static fields are initialised by applying a value in their declaration, as we have done above, they are set in the order in which they appear in the code. This means that when the ArrayB value is calculated, we are using two uninitialised values, each of which yields a result of zero." 更多信息:Doc
我正在 .NET CF 3.5 环境中开发 C# Winform 应用程序。
我了解到在下面的示例中出现了 TypeInitializationException。
static int [] ArrayB = new int [ArrayA.Length];
static int [] ArrayA = new int [] {1, 2, 3, 4};
这是因为在声明ArrayB 时ArrayA 为空。所以按照下图改就不会报错了。
static int [] ArrayA = new int [] {1, 2, 3, 4};
static int [] ArrayB = new int [ArrayA.Length];
那么为什么下面的例子没有抛出 TypeInitializationException?
static int [] ArrayB = new int [len];
static int len = 4;
ArrayB 在 len 之前声明。我认为应该发生错误,因为在声明 ArrayB 时 len 尚未初始化。
但是为什么没有出现错误呢?
即使它没有抛出异常,ArrayB 的长度仍然为零(int 的默认值)。这是某人的解释:"The cause of the unexpected value can be found in the C# Language Specification. This is the definitive documentation for C# syntax and usage. The document specifies that static fields can never be seen as uninitialised values. If they are accessed before a value has been applied, the default value for their data type is returned. For integer values, this is zero. The C# Language Specification also tells us that when static fields are initialised by applying a value in their declaration, as we have done above, they are set in the order in which they appear in the code. This means that when the ArrayB value is calculated, we are using two uninitialised values, each of which yields a result of zero." 更多信息:Doc