C# '' 的类型初始值设定项引发异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18315473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:53:35  来源:igfitidea点击:

The type initializer for '' threw an exception

c#.netexception

提问by Pinu

Consider this code:

考虑这个代码:

public class CountEnum : EnumDataType
    {
        public static readonly CountEnum CANADA = new CountEnum("CA", "Canada");
        public static readonly CountEnum DEFAULT = new CountEnum();
        private static readonly EnumDataTypeList OPTIONS = new EnumDataTypeList();
        public static readonly CountEnum UNITED_STATES = new CountEnum("US", "United States");
        public static readonly CountEnum UNSET = new CountEnum();


        private CountEnum()
        {
        }

        private CountEnum(string code, string name)
        {
            base.code = code;
            base.name = name;
            OPTIONS.Add(this); // This is the line 23
        }

Below are the exception details:

以下是异常详情:

System.TypeInitializationException was caught
  Message=The type initializer for 'CP.BusinessLogic.VConfig' threw an exception.
  Source=CP.BusinessLogic
  TypeName=CP.BusinessLogic.VConfig
  StackTrace:
       at CP.BusinessLogic.VConfig.get_Instance()
       at CP.Fac.CPFac.GetActs() in C:\tfs_src\TeamProject\Main\Source\DApp\CPApp\Fac\CPFac.cs:line 170
  InnerException: System.TypeInitializationException
       Message=The type initializer for 'CP.Types.CountEnum' threw an exception.
       Source=CP.BusinessLogic
       TypeName=CP.Types.CountEnum
       StackTrace:
            at CP.BusinessLogic.VConfig..ctor() in C:\tfs_src\TeamProject\Main\Source\DApp\CPApp\BusinessLogic\VConfig.cs:line 14
            at CP.BusinessLogic.VConfig..cctor() in C:\tfs_src\TeamProject\Main\Source\DApp\CPApp\BusinessLogic\VConfig.cs:line 11
       InnerException: System.NullReferenceException
            Message=Object reference not set to an instance of an object.
            Source=CP.DataObject
            StackTrace:
                 at CP.Types.CountEnum..ctor(String code, String name) in C:\tfs_src\TeamProject\Main\Source\DApp\CPApp\Types\CountEnum.cs:line 23
                 at CP.Types.CountEnum..cctor() in C:\tfs_src\TeamProject\Main\Source\DApp\CPApp\Types\CountEnum.cs:line 8
            InnerException:

I am unable to figure out why I am getting this exception at runtime. I am not getting any build errors and the code looks correct.

我无法弄清楚为什么我在运行时收到此异常。我没有收到任何构建错误,代码看起来是正确的。

采纳答案by Jon Skeet

Judging by your stack trace, I think you've missed out the guilty code. For example, maybe it actuallylooks like this:

从您的堆栈跟踪来看,我认为您错过了有罪的代码。例如,也许它实际上是这样的:

public class CountEnum
{
   public static readonly CountEnum DEFAULT = new CountEnum();
   private static readonly List<CountEnum> AllInstances = new List<CountEnum>();

   private CountEnum()
   {
       AllInstances.Add(this);
   }
}

That would behave the way the stack trace shows, with the CountEnumconstructor throwing a NullReferenceException. However, we can't tell for sure as you haven't included the body of the CountEnumconstructor (or indeed posted valid code for CountEnumat all).

这将按照堆栈跟踪显示的方式运行,CountEnum构造函数抛出一个NullReferenceException. 但是,我们无法确定,因为您还没有包含CountEnum构造函数的主体(或者实际上根本没有发布有效代码CountEnum)。

Fundamentally though, this is the bit of the stack trace you should be looking at:

不过,从根本上说,这是您应该查看的堆栈跟踪的一部分:

InnerException: System.NullReferenceException
     Message=Object reference not set to an instance of an object.
     Source=CP.DataObject
     StackTrace:
          at CP.Types.CountEnum..ctor(String code, String name) in C:\...\CountEnum.cs:line 23
          at CP.Types.CountEnum..cctor() in C:\...\CountEnum.cs:line 8

You should be looking at line 23 of CountEnum.cs- that's what's throwing the exception.

您应该查看第 23 行CountEnum.cs- 这就是抛出异常的原因。

EDIT: Okay, now we can see the code in question, it's very similar to my guess. Look at this code:

编辑:好的,现在我们可以看到有问题的代码,它与我的猜测非常相似。看看这段代码:

public static readonly CountEnum CANADA = new CountEnum("CA", "Canada");
public static readonly CountEnum DEFAULT = new CountEnum();
private static readonly EnumDataTypeList OPTIONS = new EnumDataTypeList();

These variables will be initialized in the order you've specified - so the call to CountEnum("CA", "Canada")will execute before OPTIONShas a non-null value... and when you try to add it to OPTIONS, you'll get an exception in a perfectly normal way.

这些变量将按照您指定的顺序进行初始化 - 因此调用CountEnum("CA", "Canada")将在OPTIONS具有非空值之前执行...并且当您尝试将其添加到 时OPTIONS,您将以完全正常的方式收到异常。

You canfix this just by moving the declaration of OPTIONSto the top:

可以通过将声明OPTIONS移到顶部解决此问题:

private static readonly EnumDataTypeList OPTIONS = new EnumDataTypeList();
public static readonly CountEnum CANADA = new CountEnum("CA", "Canada");
public static readonly CountEnum DEFAULT = new CountEnum();

That's guaranteed to work, but it's a fairly brittle design. I haveused designs like this in the past, but you can get into fiddly messes when you require a particular initialization order.

这保证有效,但这是一个相当脆弱的设计。我过去曾使用过这样的设计,但是当您需要特定的初始化顺序时,您可能会陷入混乱。