cfi*_*her 4 c# constructor static-constructor readonly
有这样的代码:
public static readonly bool MaximumRecipientsReached;
private static readonly IList<EmailAddress> Contacts;
static AdditionalRecipient()
{
Contacts = AnotherClass.Contacts; //works
}
public AdditionalRecipient()
{
MaximumRecipientsReached = true; //works not
}
Run Code Online (Sandbox Code Playgroud)
为什么我可以更改私有静态只读字段而不是公共字段?
PS:我当然正在使用属性.
Jam*_*are 12
在第一个示例中,您将在静态构造函数中更改它,这是允许的,如果您在任何其他静态方法/属性中更改它,那将是编译器错误.
在第二个示例中,您尝试更改static readonly非静态构造函数中的成员,这是不允许的.
您只能static readonly在static构造函数中更改成员.可以这样想,static构造函数运行一次,然后为每个实例调用实例构造函数.readonly如果每个实例都可以改变它,那么该属性就不会很好.
当然,您可以static readonly在构造函数中更改非实例成员:
public static readonly bool MaximumRecipientsReached = false;
public readonly bool MyInstanceReadonly = false;
static AdditionalRecipient()
{
// static readonly can only be altered in static constructor
MaximumRecipientsReached = true;
}
public AdditionalRecipient()
{
// instance readonly can be altered in instance constructor
MyInstanceReadonly = true;
}
Run Code Online (Sandbox Code Playgroud)
另外,我对你的"PS:当然我正在使用属性"感到困惑.无法声明属性readonly,如果您希望这些属性为属性并且为readonly-ish,则需要创建它们private set- 除非您使用的是后备字段.我提出这个问题的主要原因是因为使用具有私有集的属性将允许您执行代码尝试执行的操作,因为类本身可以在任何方法或构造函数中更改属性(静态或实例),但代码课外不能.
// public getters, private setters...
public static bool MaximumRecipientsReached { get; private set; }
public static IList<EmailAddress> Contacts { get; private set; }
Run Code Online (Sandbox Code Playgroud)