Essential C# 3.0 FOR NET FRAMEWORK 3.5 PHẦN 4

Phương pháp tiếp cận của ông sẽ đưa bạn từng bước thông qua cấu trúc và cú pháp của ngôn ngữ, làm cho nó dễ dàng để hiểu những điều làm việc như thế nào. Tôi tìm thấy các mẫu mã cực kỳ hữu ích và hỗ trợ các khái niệm đang được thảo luận. " | 216 Chapter 5 Classes classes can only read but whose values you can change internally. Alternatively perhaps you want to allow access to write some data in a class but you need to be able to validate changes made to the data. Still one more example is the need to construct the data on the fly. Traditionally languages enabled the features found in these examples by marking fields as private and then providing getter and setter methods for accessing and modifying the data. The code in Listing changes both FirstName and LastName to private fields. Public getter and setter methods for each field allow their values to be accessed and changed. Listing Declaring Getter and Setter Methods class Employee private string FirstName FirstName getter public string GetFirstName return FirstName FirstName setter public void SetFirstName string newFirstName if newFirstName null newFirstName FirstName newFirstName private string LastName LastName getter public string GetLastName return LastName LastName setter public void SetLastName string newLastName if newLastName null newLastName LastName newLastName . Properties 217 Unfortunately this change affects the programmability of the Employee class. No longer can you use the assignment operator to set data within the class nor can you access data without calling a method. Declaring a Property Considering the frequency of this type of pattern the C designers decided to provide explicit syntax for it. This syntax is called a property see Listing and Output . Listing Defining Properties class Program static void Main Employee employee new Employee Call the FirstName property s setter. Inigo Call the FirstName property s getter. class Employee FirstName property public string FirstName get return _FirstName set _FirstName value _ . private string _FirstName LastName property public string LastName get return _LastName set 218 Chapter 5 Classes _LastName

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.