9

环境:C#6、Visual Studio 2015 CTP 6

给定以下示例:

namespace StaticCTOR
{
  struct SavingsAccount
  {
      // static members

      public static double currInterestRate = 0.04;

      static SavingsAccount()
      {
          currInterestRate = 0.06;
          Console.WriteLine("static ctor of SavingsAccount");
      }
      //

      public double Balance;
  }

  class Program
  {
      static void Main(string[] args)
      {
          SavingsAccount s1 = new SavingsAccount();

          s1.Balance = 10000;

          Console.WriteLine("The balance of my account is \{s1.Balance}");

          Console.ReadKey();
      }
  }

}

由于某种原因,静态 ctor 没有被执行。如果我将 SavingsAccount 声明为一个类而不是一个结构,它就可以正常工作。

4

2 回答 2

13

未执行静态构造函数,因为您没有使用该结构的任何静态成员。

如果使用静态成员currInterestRate,则首先调用静态构造函数:

Console.WriteLine(SavingsAccount.currInterestRate);

输出:

static ctor of SavingsAccount
0,06

当你使用一个类时,静态构造函数会在实例创建之前被调用。为结构调用构造函数不会创建实例,因此不会触发静态构造函数。

于 2015-04-23T20:14:25.483 回答
0

根据 CLI 规范:

如果未标记 BeforeFieldInit 则该类型的初始化方法在以下位置执行(即,由以下方式触发):

  1. 首次访问该类型的任何静态字段,或
  2. first invocation of any static method of that type, or
  3. first invocation of any instance or virtual method of that type if it is a value type or
  4. first invocation of any constructor for that type

For structs which have an implicit default constructor it is not actually invoked, so you can create an instance and access its fields. Everything else (invoking custom constructors, instance property access, method calls, static field access) will trigger static constructor invocation. Also note that invoking inherited Object methods which are not overridden in the struct (e.g. ToString()) will not trigger static constructor invocation.

于 2020-01-15T14:57:13.577 回答