文档详情

C应用软件开发2.ppt

发布:2015-09-12约1.08万字共37页下载文档
文本预览下载声明
Property Methods Price Property for InventoryItem class Using the Price Property Property Methods Read-only Properties Some properties should be read-only. Their value should be controlled by other methods. In the following example, the Description property is read-only, set just once in the constructor. To make a property read-only, leave out the set portion. Property Methods Calculated Properties Some properties do not require a corresponding instance variable. Their value can be calculated each time the property is invoked. Calculated properties should be read-only. Another example: the Area property of a Rectangle class. There is no need to store the area in a separate instance variable when the class already stores the width and height. Automatic Properties class Person { private string lastName; public string LastName { get { return lastName; } set { lastName = value; } } . . . } class Person { public string LastName { get; set;} . . . } class Person { public string LastName { get; private set;} . . . } Automatic Properties Shorthand Property definition “Backing Field” automatically created by the compiler Does not support “calculated” properties (use a Property Method) Can simulate a ReadOnly property by scoping the set as private (Removing the set will not work) Backing fields are initialized to their “default” values numerics = 0 bool = false reference types = null string = null Object Initializers class Person { public string FirstName { get; set;} public string LastName { get; set;} public Person(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } } class Program { static void Main() { Person person = new Person(“Moe”, “Howard”); } } Object Initializers class Person { public string FirstName { get; set; } public string LastName { get; set; } } class Program { static void Main() { Person person = new Person { FirstName = “Moe”, Lastname =
显示全部
相似文档