tailieunhanh - Working with Structure Types

Làm việc với Cơ cấu loại Bạn đã thấy trong Chương 8 rằng các lớp học xác định các loại tài liệu tham khảo được luôn luôn tạo ra trên heap. Trong một số trường hợp, các lớp có thể chứa dữ liệu rất ít mà những phí quản lý trở nên không cân xứng heap | Working with Structure Types You saw in Chapter 8 that classes define reference types that are always created on the heap. In some cases the class can contain so little data that the overhead of managing the heap becomes disproportionate. In these cases it is better to define the type as a structure. Because structures are stored on the stack the memory management overhead is often reduced as long as the structure is reasonably small . A structure can have its own fields methods and constructors just like a class and unlike an enumeration but it is a value type and not a reference type. Common Structure Types You may not have realized it but you have already used structures in previous exercises in this book. In C the primitive numeric types int long and float are aliases for the structures and respectively. This means that you can actually call methods on variables and literals of these types. For example all of these structures provide a ToString method that can convert a numeric value to its string representation. The following statements are all legal statements in C int i 99 float f You don t see this use of the ToString method very often because the method calls it automatically when it is needed. Use of the static methods exposed by these structures is much more common. For example in earlier chapters the static method was used to convert a string to its corresponding integer value string s 42 int i s NOTE Because int is simply an alias for Int32 you can also use . These structures also include some useful static fields. For example is the maximum value that an int can hold and is the smallest value you can store in an int. The following table shows the primitive types in C their equivalent types in the .NET .