【发布时间】:2015-07-02 05:18:19
【问题描述】:
环境: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 声明为一个类而不是一个结构,它就可以正常工作。
【问题讨论】:
-
查看this link,了解如何在结构中设置无参数构造函数。
标签: c# visual-studio visual-studio-2015 static-constructor c#-6.0