หมายเหตุ
การเข้าถึงหน้านี้ต้องได้รับการอนุญาต คุณสามารถลอง ลงชื่อเข้าใช้หรือเปลี่ยนไดเรกทอรีได้
การเข้าถึงหน้านี้ต้องได้รับการอนุญาต คุณสามารถลองเปลี่ยนไดเรกทอรีได้
The contextual keyword field, added in C# 14, can be used in a property accessor to access the compiler synthesized backing field of a property. This syntax enables you to define the body of a get or set accessor and let the compiler generate the other accessor as it would in an automatically implemented property.
The addition of the field contextual keywords provides a smooth path to add benefits such as range checking to an automatically implemented property. This practice is shown in the following example:
class TimePeriod4
{
public double Hours {
get;
set => field = (value >= 0)
? value
: throw new ArgumentOutOfRangeException(nameof(value), "The value must not be negative");
}
}
You might implement the Hours property as an automatically implemented property. Then, you discover that you want to protect against a negative value. You use field and provide range checking in the set accessor. You don't need to declare the backing field by hand and provide a body for the get accessor.
For more information, see the Properties and Indexers articles.
C# language specification
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.