tailieunhanh - Thinking in C# phần 3

Mỗi đối tượng tiếp tục lưu trữ riêng của mình cho các thành viên dữ liệu của nó, các thành viên dữ liệu không được chia sẻ giữa các đối tượng. Dưới đây là một ví dụ của một lớp học với một số thành viên dữ liệu: public class DataOnly {public int i; e nổi công cộng, công bool b; private string s;} | using System Demonstration of a simple constructor. public class Rock2 public Rock2 int i This is the constructor Creating Rock number i public class SimpleConstructor public static void Main for int i 0 i 10 i new Rock2 i Constructor arguments provide you with a way to provide parameters for the initialization of an object. For example if the class Tree has a constructor that takes a single integer argument denoting the height of the tree you would create a Tree object like this I Tree t new Tree 12 12-foot tree If Tree int is your only constructor then the compiler won t let you create a Tree object any other way. Constructors eliminate a large class of problems and make the code easier to read. In the preceding code fragment for example you don t see an explicit call to some initialize method that is conceptually separate from definition. In C definition and initialization are unified concepts you can t have one without the other. The constructor is an unusual type of method because it has no return value. This is distinctly different from a void return value in which the method is declared explicity as returning nothing. With constructors you are not given a choice of what you return a constructor always returns an object of the constructor s type. If there was a declared return value and if you could select your own the compiler would somehow need to know what to do with that return value. Accidentally typing a return type such as void before declaring a constructor is a common thing to do on a Monday morning but the C compiler won t allow it telling you member names cannot be the same as their enclosing type. Chapter 5 Initialization Cleanup 151 Method overloading One of the important features in any programming language is the use of names. When you create an object you give a name to a region of storage. A method is a name for an action. By using names to describe your system you create a program that is easier for people to understand and

TỪ KHÓA LIÊN QUAN