- readonly (C# Reference)
- readonly 关键字是可以在字段上使用的修饰符。 当字段声明包括 readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分出现,或者出现在同一类的构造函数中
class Age
{
readonly int _year;
Age(int year)
{
_year = year;
}
void ChangeYear()
{
//_year = 1967; // Compile error if uncommented.
}
}- readonly 关键字与 const 关键字不同。
- const 字段只能在该字段的声明中初始化。
- readonly 字段可以在声明或构造函数中初始化。 因此,根据所使用的构造函数,readonly 字段可能具有不同的值。 另外,const 字段为编译时常数,而 readonly 字段可用于运行时常数
- Thread lock
-
private class FakeRepoGenerator
{
private static int _callCount = 0; public static Task<RepositoryTableEntity> Generate()
{
var entity = Interlocked.Increment(ref _callCount) == 1 ? null : ControllerUnitTestHelper.DefaultRepositoryTableEntity;
return Task.FromResult(entity);
}
}
-