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 (9.08 KB, 2 trang )
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 3.141592 * 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