环境: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();
}
}
静态构造器由于某种原因没有被执行。如果我将 SavingsAccount 声明为类而不是结构,它就可以正常工作。
最佳答案
静态构造函数未执行,因为您没有使用该结构的任何静态成员。
如果使用静态成员currInterestRate
,则首先调用静态构造函数:
Console.WriteLine(SavingsAccount.currInterestRate);
输出:
static ctor of SavingsAccount
0,06
当您使用一个类时,静态构造函数将在创建实例之前被调用。为结构调用构造函数不会创建实例,因此不会触发静态构造函数。
关于c# - 静态构造函数不适用于结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29833312/