Working with Structure Types
Số trang: 11
Loại file: pdf
Dung lượng: 34.50 KB
Lượt xem: 11
Lượt tải: 0
Xem trước 2 trang đầu tiên của tài liệu này:
Thông tin tài liệu:
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
Nội dung trích xuất từ tài liệu:
Working with Structure Types Working with Structure TypesYou saw in Chapter 8 that classes define reference types that are always created on theheap. In some cases, the class can contain so little data that the overhead of managing theheap 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 oftenreduced (as long as the structure is reasonably small).A structure can have its own fields, methods, and constructors just like a class (and unlikean enumeration), but it is a value type and not a reference type.Common Structure TypesYou may not have realized it, but you have already used structures in previous exercisesin this book. In C#, the primitive numeric types int, long, and float, are aliases for thestructures System.Int32, System.Int64, and System.Single, respectively. This means thatyou can actually call methods on variables and literals of these types. For example, all ofthese structures provide a ToString method that can convert a numeric value to its stringrepresentation. The following statements are all legal statements in C#:int i = 99;Console.WriteLine(i.ToString());Console.WriteLine(55.ToString());float f = 98.765F;Console.WriteLine(f.ToString());Console.WriteLine(98.765F.ToString());You dont see this use of the ToString method very often, because the Console.WriteLinemethod calls it automatically when it is needed. Use of the static methods exposed bythese structures is much more common. For example, in earlier chapters the staticInt32.Parse method was used to convert a string to its corresponding integer value:string s = 42;int i = Int32.Parse(s);NOTEBecause int is simply an alias for Int32, you can also use int.Parse.These structures also include some useful static fields. For example, Int32.MaxValue isthe maximum value that an int can hold, and Int32.MinValue is the smallest value youcan store in an int.The following table shows the primitive types in C#, their equivalent types in the .NETFramework, and whether each type is a class or structure.Keyword Type equivalent Class or structurebool System.Boolean Structurebyte System.Byte Structuredecimal System.Decimal StructureDouble System.Double StructureFloat System.Single StructureInt System.Int32 StructureLong System.Int64 StructureObject System.Object ClassSbyte System.SByte StructureShort System.Int16 StructureString System.String ClassUint System.UInt32 StructureUlong System.UInt64 StructureUshort System.UInt16 StructureDeclaring Structure TypesTo declare your own structure value type, you use the struct keyword followed by thename of the type, followed by the body of the structure between opening and closingbraces. For example, here is a struct called Time that contains three public int fieldscalled hours, minutes, and seconds:struct Time{ public int hours, minutes, seconds;}As with classes, making the fields of a structure public is not advisable in most cases;there is no way to ensure that public fields contain valid values. For example, anyonecould set the value of minutes or seconds to a value greater than 60. A better idea is tomake the fields private and provide your structure with constructors and methods, asshown in this example:struct Time{ public Time(int hh, int mm, int ss) { hours = hh % 24; minutes = mm % 60; seconds = ss % 60; } public int Hours() { return hours; } ... private int hours, minutes, seconds;}NOTEBy default, you cannot use many of the common operators on your own structure types.For example, you cannot use operators such as == and != on your own struct typevariables. However, you can explicitly declare and implement operators for your ownstruct types. The syntax for doing this is covered in Chapter 19.Use structs to implement simple concepts whose main feature is their value. For example,an int is a value type because its main feature is its value. If you have two int variablesthat contain the same value (such as 42), one is as good as the other. When you copy avalue type variable, you get two copies of the value. In contrast, when you copy areference type variable, you get two references to the same object. In summary, usestructs for lightweight concepts where it makes sense to copy the value, and use classesfor more heavyweight concepts where it doesnt make sense to copy the value.Understanding Structure and Class DifferencesA structure and a class are syntactically very similar but there are a few importantdifferences. Lets look at some of these differences. • You cant declare a default constructor (a constructor with no parameters) for a struct. The following example would compile if Time were a class, but because Time is a struct it fails to c ...
Nội dung trích xuất từ tài liệu:
Working with Structure Types Working with Structure TypesYou saw in Chapter 8 that classes define reference types that are always created on theheap. In some cases, the class can contain so little data that the overhead of managing theheap 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 oftenreduced (as long as the structure is reasonably small).A structure can have its own fields, methods, and constructors just like a class (and unlikean enumeration), but it is a value type and not a reference type.Common Structure TypesYou may not have realized it, but you have already used structures in previous exercisesin this book. In C#, the primitive numeric types int, long, and float, are aliases for thestructures System.Int32, System.Int64, and System.Single, respectively. This means thatyou can actually call methods on variables and literals of these types. For example, all ofthese structures provide a ToString method that can convert a numeric value to its stringrepresentation. The following statements are all legal statements in C#:int i = 99;Console.WriteLine(i.ToString());Console.WriteLine(55.ToString());float f = 98.765F;Console.WriteLine(f.ToString());Console.WriteLine(98.765F.ToString());You dont see this use of the ToString method very often, because the Console.WriteLinemethod calls it automatically when it is needed. Use of the static methods exposed bythese structures is much more common. For example, in earlier chapters the staticInt32.Parse method was used to convert a string to its corresponding integer value:string s = 42;int i = Int32.Parse(s);NOTEBecause int is simply an alias for Int32, you can also use int.Parse.These structures also include some useful static fields. For example, Int32.MaxValue isthe maximum value that an int can hold, and Int32.MinValue is the smallest value youcan store in an int.The following table shows the primitive types in C#, their equivalent types in the .NETFramework, and whether each type is a class or structure.Keyword Type equivalent Class or structurebool System.Boolean Structurebyte System.Byte Structuredecimal System.Decimal StructureDouble System.Double StructureFloat System.Single StructureInt System.Int32 StructureLong System.Int64 StructureObject System.Object ClassSbyte System.SByte StructureShort System.Int16 StructureString System.String ClassUint System.UInt32 StructureUlong System.UInt64 StructureUshort System.UInt16 StructureDeclaring Structure TypesTo declare your own structure value type, you use the struct keyword followed by thename of the type, followed by the body of the structure between opening and closingbraces. For example, here is a struct called Time that contains three public int fieldscalled hours, minutes, and seconds:struct Time{ public int hours, minutes, seconds;}As with classes, making the fields of a structure public is not advisable in most cases;there is no way to ensure that public fields contain valid values. For example, anyonecould set the value of minutes or seconds to a value greater than 60. A better idea is tomake the fields private and provide your structure with constructors and methods, asshown in this example:struct Time{ public Time(int hh, int mm, int ss) { hours = hh % 24; minutes = mm % 60; seconds = ss % 60; } public int Hours() { return hours; } ... private int hours, minutes, seconds;}NOTEBy default, you cannot use many of the common operators on your own structure types.For example, you cannot use operators such as == and != on your own struct typevariables. However, you can explicitly declare and implement operators for your ownstruct types. The syntax for doing this is covered in Chapter 19.Use structs to implement simple concepts whose main feature is their value. For example,an int is a value type because its main feature is its value. If you have two int variablesthat contain the same value (such as 42), one is as good as the other. When you copy avalue type variable, you get two copies of the value. In contrast, when you copy areference type variable, you get two references to the same object. In summary, usestructs for lightweight concepts where it makes sense to copy the value, and use classesfor more heavyweight concepts where it doesnt make sense to copy the value.Understanding Structure and Class DifferencesA structure and a class are syntactically very similar but there are a few importantdifferences. Lets look at some of these differences. • You cant declare a default constructor (a constructor with no parameters) for a struct. The following example would compile if Time were a class, but because Time is a struct it fails to c ...
Gợi ý tài liệu liên quan:
-
Giáo trình Lập trình hướng đối tượng: Phần 2
154 trang 271 0 0 -
Bài thuyết trình Ngôn ngữ lập trình: Hệ điều hành Window Mobile
30 trang 263 0 0 -
Kỹ thuật lập trình trên Visual Basic 2005
148 trang 262 0 0 -
Giáo trình Lập trình cơ bản với C++: Phần 1
77 trang 230 0 0 -
Bài giảng Một số hướng nghiên cứu và ứng dụng - Lê Thanh Hương
13 trang 221 0 0 -
Giáo án Tin học lớp 11 (Trọn bộ cả năm)
125 trang 214 1 0 -
NGÂN HÀNG CÂU HỎI TRẮC NGHIỆM THIẾT KẾ WEB
8 trang 203 0 0 -
Bài tập lập trình Windows dùng C# - Bài thực hành
13 trang 179 0 0 -
Giáo trình Lập trình C căn bản: Phần 1
64 trang 169 0 0 -
Bài giảng Nhập môn về lập trình - Chương 1: Giới thiệu về máy tính và lập trình
30 trang 163 0 0