静态构造函数不适用于结构

Bru*_*tos 8 c# static-constructor visual-studio c#-6.0 visual-studio-2015

环境: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();
      }
  }
Run Code Online (Sandbox Code Playgroud)

}

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

Guf*_*ffa 13

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

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

Console.WriteLine(SavingsAccount.currInterestRate);
Run Code Online (Sandbox Code Playgroud)

输出:

static ctor of SavingsAccount
0,06
Run Code Online (Sandbox Code Playgroud)

使用类时,将在创建实例之前调用静态构造函数.为结构调用构造函数不会创建实例,因此它不会触发静态构造函数.