Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (17.83 KB, 2 trang )
Understanding the Property Restrictions
Properties look, act, and feel like fields. However, they are not true fields, and certain
restrictions apply to them:
•
You can't initialize a property of a struct or class by using a set accessor. The code
in the following example is illegal as the location variable has not been initialized
(by using new):
•
ScreenPosition location;
location.X = 40; // compile-time error, location not assigned
NOTE
This may seem trivial, but if X was a field rather than a property, the code would
be legal. What this really means is that there are some differences between fields
and properties. You should define structs and classes by using properties from the
start, rather than by using fields that you later migrate to properties—code that
uses your classes and structs might no longer work if you change fields into
properties.
•
You can't use a property as a ref or out argument (whereas you can use a writeable
field as a ref or out argument). For example:
MyMethod(ref location.X); // compile-time error
•
A property can contain at most one get accessor and one set accessor. A property
cannot contain other methods, fields, or properties.
•
The get and set accessors cannot take any parameters. The data being assigned is
passed to the set accessor automatically, by using the value variable.
•
You can't declare const or readonly properties. For example: