Defining and Using a Class

Xác định và sử dụng một Class trong C #, bạn sử dụng từ khoá class, tên, và một cặp dấu ngoặc nhọn để định nghĩa một lớp mới. Các dữ liệu và phương pháp của lớp học xảy ra trong cơ thể của lớp, giữa các dấu ngoặc nhọn. | Defining and Using a Class In C you use the class keyword a name and a pair of curly braces to define a new class. The data and methods of the class occur in the body of the class between the curly braces. Here is a C class called Circle that contains one method to calculate the circle s area and one piece of data the circle s radius class Circle double Area return radius radius double radius The body of a class contains ordinary methods such as Area and fields such as radius remember that variables in a class are called fields. You ve already seen how to declare variables in Chapter 2 Working with Variables Operators and Expressions and how to write methods in Chapter 3 Writing Methods and Applying Scope in fact there s almost no new syntax here. Using the Circle class is similar to using other types that you have already met you create a variable specifying Circle as its type and then you initialize the variable with some valid data. Here is an example Circle c Create a Circle variable c new Circle Initialize it Note the use of the new keyword. Previously when you initialized a variable such as an int or a float you simply assigned it a value int i i 42 You cannot do the same with variables of class types. One reason is that C just doesn t provide the syntax for assigning literal class values to variables. What is the Circle equivalent of 42 Another reason concerns the way in which memory for variables of class types is allocated and managed by the common language runtime this will be discussed further in Chapter 8 Understanding Values and References. For now just accept that the new keyword creates a new instance of a class more commonly called an object . IMPORTANT Don t get confused between the terms class and object. A class is the definition of a type. An object is an instance of that type created when the program runs. For example it is possible to create many instances of the Circle class in a program by using the new keyword just as you can .

Bấm vào đây để xem trước nội dung
TÀI LIỆU MỚI ĐĂNG
80    375    2    01-06-2024
Đã 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.