⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch01.htm

📁 delphi自学的好教材!特别适合刚刚起步学习delphi的人员!同样对使用者具有参考价值!
💻 HTM
📖 第 1 页 / 共 5 页
字号:
</BLOCKQUOTE><P>There is a third type of unit you can use in Delphi applications. This type ofunit is a unit that contains only source code. A code-only unit contains code thatis called from other units in the project. I won't go into any more detail than thatright now, but you'll learn more about this type of unit in later chapters.</P><P><H4>Anatomy of a Delphi Unit</H4><P>Delphi units must follow a predefined format. This shouldn't come as a surpriseto you. The unit has to be in a predefined format so that the compiler can read theunit and compile the unit's code.</P><P>A Delphi project unit contains the program keyword followed by the name of theunit and a code block marked by the begin and end keywords. You can see how a basicunit looks by choosing View | Project Source from the Delphi main menu. The projectsource unit for a default Delphi project looks like Listing 1.1.</P><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> The line numbers in Listing 1.1 are not part of the unit itself.	I have put them there for reference only. Some of the listings you see in this book	will have line numbers for reference and others will not. In either case, be sure	to understand that the Pascal language does not use line numbers as some other languages	do (most notably, BASIC). <HR></BLOCKQUOTE><P><H4>LISTING 1.1. THE PROJECT SOURCE FOR A DEFAULT DELPHI PROJECT.</H4><PRE>01: program Project1;02: 03: uses04:   Forms,05:   Unit1 in `Unit1.pas' {Form1};06:07: {$R *.RES}08:09: begin10:   Application.Initialize;11:   Application.CreateForm(TForm1, Form1);12:   Application.Run;13: end.</PRE><P>On line 1, the program keyword identifies this unit as a program's main sourceunit. You can see that the unit name, Project1, follows the program keyword (Delphigives the project a default name until you save the project with a more meaningfulname). Beginning on line 3, you see a section identified by the uses keyword. Anyunit names following the uses keyword, up to the semicolon, are other units thatthis unit requires in order to compile. The uses keyword is described in more detaila little later in the section, &quot;The uses List.&quot;</P><P>On line 7 you see a compiler directive that tells Delphi to include this project'sresource file. Resource files are discussed in more detail on Day 8, &quot;CreatingApplications in Delphi.&quot;</P><P>Line 9 contains the begin keyword, and line 13 contains the end keyword. Noticethat the final end keyword in the unit is followed by a period. (A unit can havemany code blocks marked with begin and end, but only one final end statement.) Thecode on lines 10, 11, and 12 is code that initializes the application, creates theapplication's main form, and starts the application running. You don't need to beconcerned about the details of this code to write Delphi programs.</P><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> The begin and end keywords mark a code block. A code block can contain	just a few lines of code, or it can contain several hundred lines of code (or even	thousands of lines). You will see the begin and end keywords used throughout the	book. As you work through the book, you will get a better handle on how and when	the begin and end keywords are used. <HR></BLOCKQUOTE><P>Let's take a look at another basic Pascal unit. Choose File | New from the mainmenu. When the New Items dialog comes up, locate the icon labeled Unit and double-clickit. Delphi will create a new unit and display it in the Code Editor. Listing 1.2shows the code generated for this unit.</P><P><H4>LISTING 1.2. A BLANK PASCAL UNIT.</H4><PRE>01: unit Unit2;02:03: interface04:05: implementation06:07: end.</PRE><PRE>There isn't much here, is there? This unit has two things in common with the unit shown in Listing 1.1. First, the unit starts with the unit keyword followed by the unit name Unit2 (again, a default name created by Delphi). I realize the code in Listing 1.1 starts with the program keyword and this code starts with the unit keyword, but there are a few common elements: A Pascal unit starts with one of these two keywords followed by the unit name, and the end keyword appears at the end of both listings. Here again, the end keyword is followed by a period to mark the end of the unit.</PRE><P>The code in Listing 1.2 differs from that of Listing 1.1 in that it has sectionsmarked interface and implementation. A unit that is not the program's main sourceunit must contain an interface section and an implementation section. These two keywordswill be described in more detail in the sections entitled, &quot;The interface Section&quot;and &quot;The implementation Section,&quot; respectively. Listing 1.2 also differsfrom Listing 1.1 in that there is no begin statement. A program's main unit musthave both begin and end statements, but a source unit only has to contain a finalend statement.</P><P>The following sections describe keywords that are used within a Pascal unit.</P><P><H4>The uses List</H4><P><strong>New Term:</strong> The <I>uses list</I> is a list of external units that thisunit references.</P><P>Refer to Listing 1.1. Notice the uses keyword on line 3. The uses keyword designatesthe start of a section that will contain a list of other units that this unit isdependent on. For example, line 11 of Listing 1.1 looks like this:</P><P><PRE>Application.CreateForm(TForm1, Form1);</PRE><P>This line of code contains information that is located in other units and cannotbe found in this unit. The procedure identified by Application.CreateForm is locatedin a Delphi unit called Forms.pas, and the identifiers TForm1 and Form1 are locatedin the project's main form unit, which is called Unit1.pas. Do you see the connection?The uses list tells Delphi where to look for additional information that it willneed to compile this unit. Here's another look at the uses list:</P><P><PRE>uses  Forms,  Unit1 in `Unit1.pas' {Form1};</PRE><P>Notice that the uses list contains two unit names, Forms and Unit1. In some waysthis is not a good example of a uses list because the second unit listed containsadditional text not usually found in a uses list (Unit1 in `Unit1.pas' {Form1}).</P><P>This text is used to specify a form that is contained in a unit and is only usedby the project's main source unit. (The text between the curly braces is a commentused for reference and has no bearing on the rest of the code. Comments are discussedlater in the section &quot;Comments in Code.&quot;)</P><P>There are two rules you need to be aware of when constructing the uses list:</P><UL>	<LI>First, each unit in the list must be separated from the following unit by a comma.	<P>	<LI>Second, a semicolon must follow the last unit listed. The semicolon marks the	end of the uses list.</UL><P>Naturally the list must contain valid unit names. The uses list, then, is designatedby the uses keyword and ends with a semicolon. Other than that, it doesn't matterhow the uses list is organized. For example, the following two uses lists are identicalas far as the compiler is concerned:</P><P><PRE>uses  Windows, Messages, SysUtils, Classes, Graphics,   Controls, Forms, Dialogs, StdCtrls;uses  Windows,   Messages,   SysUtils,   Classes,   Graphics,   Controls,   Forms,   Dialogs,  StdCtrls;</PRE><P>A unit can have any number of uses lists. It is not required that all units neededby this unit be in a single uses list.</P><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> In some cases, Delphi will add units to your uses list for you. This	is done via the File | Use Unit menu item. This feature will be discussed in more	detail on Day 4. <HR></BLOCKQUOTE><H4><BR>The interface Section</H4><P>Take another look at Listing 1.2. Notice that this listing has a section markedby the interface keyword. This keyword marks the start of the interface section forthe unit.</P><P>The <I>interface section</I> is the section of a unit in which identifiers exportedfrom this unit are declared. An <I>exported </I>identifier is one that can be accessedby other units in the project.</P><P>Most units will contain code that other units use. The code might be implementedas a class, a procedure, a function, or a data variable. Any objects that are availableto other units from this unit must be declared in the interface section. You couldsay that the interface section contains a list of items in this unit that other unitscan use. The interface section starts with the interface keyword and ends at theimplementation keyword.</P><P><H4>The implementation Section</H4><P><strong>New Term:</strong> The <I>implementation section</I> of a unit is the sectionthat contains the actual code for the unit.</P><P>The implementation section starts with the implementation keyword and ends withthe next unit keyword. The next unit keyword is usually the unit's final end keyword,but could be the initialization keyword in units that have an initialization section.It's difficult to say more than that right now, because there are other aspects ofPascal that I need to discuss before tying all of this together. However, let megive you an example that will illustrate the use of the interface and implementationsections.</P><P>Let's say that you create a unit that has a procedure called DoSomething. Let'sfurther say you want DoSomething to be available to other units in your project.In that case, you would declare the DoSomething procedure in the interface sectionand then define the procedure in the implementation section. The entire unit wouldlook like Listing 1.3.</P><P><H4>LISTING 1.3. A UNIT WITH A PUBLIC FUNCTION.</H4><PRE>unit Unit2;interface  procedure DoSomething;implementation  procedure DoSomething;  begin</PRE><PRE>    { Code for DoSomething goes here. }</PRE><PRE>  end;end.</PRE><P>Notice that the DoSomething procedure is declared in the interface section anddefined later in the implementation section. I realize I'm getting a little aheadof myself here. Functions and procedures will be discussed more tomorrow, and I'llgo over declarations and definitions in detail at that time.</P><P><H4>The initialization and finalization Sections</H4><P>The initialization and finalization sections can be used to perform any startupand cleanup code that a unit requires. Any code in the initialization section willbe executed when the unit is loaded into memory. Conversely, any code in the finalizationsection will be executed just before the unit is unloaded from memory. You can havejust an initialization section, but you cannot have a finalization section withoutan initialization section. The initialization and finalization sections are optional.</P><P><H4>Additional Keywords Used in Units</H4><P>A Pascal unit can contain other, optional keywords that mark sections set asidefor a particular purpose. Some of these keywords have multiple uses. The followingsections describe those keywords only as they pertain to units.</P><P><B>The const Keyword</B></P><P>A unit can optionally have one or more const sections. The const section is designatedwith the const keyword. The const section describes a list of variables that areknown as constants.</P><P>A <I>constant</I> is an identifier that cannot change. For example, let's sayyou have certain values that your program uses over and over. You can set up constantvariables for those values. To illustrate, let's add a const section to the programin Listing 1.3. You'll add one const section for constants that are public (availableto other units) and another const section for constants that are available only tothis unit. Listing 1.4 shows the unit with the two const sections added.</P><P><H4>LISTING 1.4. THE UNIT WITH const SECTIONS ADDED.</H4><PRE>unit Unit2;interfaceconst  AppCaption = `My Cool Program 1.0';  procedure DoSomething;implementationconst  BaseX = 20;  BaseY = 200;  procedure DoSomething;  begin    { Code for DoSomething goes here. }  end;end.</PRE><P>Because the AppCaption constant is declared in the interface section, it can beused anywhere in the unit <I>and</I> in any unit that has this unit in its uses list.The BaseX and BaseY constants, however, are only available within this unit becausethey are declared in the implementation section.</P><P>The const keyword has other uses besides the one described here. I'll discussone of those uses tomorrow in the section, &quot;Value, Constant, and Variable Parameters.&quot;</P><P><B>The type Keyword</B></P><P><strong>New Term:</strong> The <I>type</I> keyword is used to declare new types thatyour program will use.</P><P>Declaring a new type is an esoteric programming technique that is difficult toexplain at this stage of the game, so perhaps an example will help. Let's say thatyour application needs an <I>array</I> (a collection of values) of 20 bytes and thatthis type of array will be used over and over again. You can declare a new type asfollows:</P><P><PRE>type  TMyArray = array [0..19] of Byte;</PRE><P>Now you can use the identifier TMyArray instead of typing out array [0..19] ofByte every time you want an array of 20 bytes. I'll have to leave it at that fornow, but you'll see more examples of declaring types later in the book.</P><P><B>The var Keyword</B></P><P><strong>New Term:</strong> The <I>var</I> keyword is used to declare a section of codein which variables are declared.</P><P>You use the var keyword to declare variables (variables are discussed in detailin the section entitled &quot;Variables&quot;). There are several places you candeclare a var section. You can have a var section at the unit level, you can havea var section for a procedure or function, or both. You can even have multiple varsections in a unit. Listing 1.5 shows the sample unit with type and var sectionsadded.</P><P>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -