1. Trang chủ
  2. » Công Nghệ Thông Tin

Manning Windows Forms Programming (phần 15) ppsx

50 255 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 669,79 KB

Nội dung

666 APPENDIX A C# PRIMER true As in operator in user-defined types, defines the meaning of “true” for instances of that type. public static bool operator true(MyType x) { // Return whether MyType is "true" } false As a literal, the boolean value of true. bool isAppendix = true; false; discussion in section 3.4.2, page 93 try Begins a block in which exceptions may be handled, depending on the attached catch clauses. // Open a file FileStream fs = new FileStream( ); try { // Do something with open file } catch (IOException ex) { // Handle caught exception } finally { fs.Close(); // ensure file closure } catch finally throw section 2.3.2, page 58 typeof Obtains the System.Type object for a given type. Use the Object.GetType method to obtain the type instance for an expression. Type t = typeof(Photograph); code in section 10.5.3, page 348 uint Denotes an unsigned 32-bit integer value. Use the u or U suffix to denote an integer value as a uint type. uint apprxCircum uint radius = 7u, pi = 314159; apprxCircum = 2u * pi * radius / 100000u; ulong; ushor ulong Denotes an unsigned 64-bit integer value. When using the L suffix to denote a long integer or the U suffix to denote an unsigned integer, the value is considered ulong if it is beyond the range of the long or uint type, respectively. ulong apprxCircum ulong radius = 7L; ulong pi = 31415926535 apprxCircum = 2 * pi * radius / 10000000000L); ulong; ushort unchecked Suppresses integer overflow checking on the given statement. If an overflow occurs, the result is truncated. By default, all integer expressions are checked. long bigPrime = 9876543211; long notSoBigNum = unchecked(bigPrime * bigPrime); checked C# keywords (continued) Keyword Description Example See also SPECIAL FEATURES 667 A.4 SPECIAL FEATURES This section presents some noteworthy features of the C# language. These topics did not fit in previous sections of this appendix, but are important concepts for unsafe Indicates an unmanaged region of code, in which pointers are permitted and normal runtime verification is disabled. See example for stackalloc keyword. ushort Denotes an unsigned 16-bit integer value. A cast is required to convert an int or uint value to ushort. ushort apprxCircum ushort radius = (ushort)7; ushort pi = (ushort)314; apprxCircum = (ushort)2 * pi * radius / (ushort)100; uint; ulong using As a directive, indicates a namespace from which types do not have to be fully qualified. Alternatively, indicates a shortcut, or alias, for a given class or namespace name. using System.Windows.Forms; using App = Application; public void Main() { Form f = new MainForm(); App.Run(f); } section 1.2.1 on page 15 As a statement, defines a scope for a given expression or type. At the end of this scope, the given object is disposed. using (OpenFileDialog dlg = new OpenFileDialog()) { // Do something with dlg } discussion in section 8.2.1, page 233 virtual Declares that a method or property member may be overridden in a derived class. At runtime, the override of a type member is always invoked. See example for override keyword. override; section 9.1.1, page 265 volatile Indicates that a field may be modified in a program at any time, such as by the operating system or in another thread. // Read/Write x anew for each line. volatile double x = 70.0; int num = x; x = x * Sqrt(x); void Indicates that a method does not return a value. See examples for override and protected key- words. examples throughout text while As a statement, executes a statement or block of statements until a given expression is false. Photograph p = _album.FirstPhoto; while (p != null) { // Do something with Photograph p = _album.NextPhoto; } for; foreach In a do-while loop, specifies the condition that will terminate the loop. See example for do keyword. do; C# keywords (continued) Keyword Description Example See also 668 APPENDIX A C# PRIMER programming in the language. The topics covered are exceptions, arrays, the Main entry point, boxing, and documentation. Readers more familiar with C# will recognize certain features omitted from this discussion and the book in general. These include attributes, reflection, and the pre- processor. These features, while important, were considered beyond the scope of this book, and are not required in many Windows Forms applications. A brief discussion of attributes is provided in chapter 2 as part of a discussion on the AssemblyInfo.cs file. A.4.1 E XCEPTIONS An exception is a type of error. Exceptions provide a uniform type-safe mechanism for handling system level and application level error conditions. In the .NET Frame- work, all exceptions inherit from the System.Exception class. Even system-level errors such as divide-by-zero and null references have well-defined exception classes. If a program or block of code ignores exceptions, then exceptions are considered unhandled. By default, an unhandled exception immediately stops execution of a pro- gram. 2 This ensures that code which ignores exceptions does not continue processing when an error occurs. Code that does not ignore exceptions is said to handle excep- tions, and must indicate the specific set of exception classes that are handled by the code. An exception is said to be handled or caught if a block of code can continue pro- cessing after an exception occurs. Code which generates an exception is said to throw the exception. The try keyword is used to indicate a block of code that handles exceptions. The catch keyword indicates which exceptions to explicitly handle. The finally key- word is used to indicate code that should be executed regardless of whether an excep- tion occurs. Code that handles one or more exceptions in this manner uses the following format: try <try-block> <catch-blocks> opt <finally-block> opt where • <try-block> is the set of statements, enclosed in braces, that should handle exceptions. • <catch-blocks> is optional, and consists of one or more catch blocks as defined below. 2 Well, most of the time. If an unhandled exception occurs during the execution of a static constructor, then a TypeInitializationException is thrown rather than the program exiting. In this case, the original exception is included as the inner exception of the new exception. SPECIAL FEATURES 669 • <finally-block> is optional, and consists of the finally keyword fol- lowed by the set of statements, enclosed in braces, that should execute whether or not an exception occurs. The format of a try block allows for one or more catch blocks, also called catch clauses, to define which exceptions to process. These are specified with the catch keyword in the following manner: catch <exception> opt <catch-block> where • <exception> is optional, and indicates the exception this catch clause will handle. This must be a class enclosed in parenthesis with an optional identifier that the block will use to reference this exception. If no class is provided, then all exceptions are handled by the clause. • <catch-block> is the set of statements, enclosed in braces, that handles the given exception. For example, one use for exceptions is to handle unexpected conversion errors, such as converting a string to an integer. The following side-by-side code contrasts two ways of doing this: When an exception occurs in a program that satisfies more than one catch block within the same try block, the first matching block is executed. For this reason, the more distinct exceptions should appear first in the list of catch blocks. As an example, consider the IOException class, which is thrown when an unexpected I/O error occurs. This class derives from the Exception class. The following code shows how an exception block might be written to handle exceptions that might occur while reading a file: // Open some file system object FileStream f = new FileStream( ); // A string theString requires conversion int version = 0; try { version = Convert.ToInt32(theString); } catch { version = 0; } // A string theString requires conversion int version = 0; try { version = Convert.ToInt32(theString); } catch (FormatException) { version = 0; } If any exception occurs while converting the string to an int, then the catch clause will set version to 0. For example, if the theString variable is null, an ArgumentException will occur, and version will still be set to 0. The catch clause will set version to 0 only if a FormatException exception occurs while converting the string to an int. Any other exception is unhandled and will exit the program if not handled by a previous method. 670 APPENDIX A C# PRIMER try { //Code that makes use of FileStream object } catch (IOException ioex) { // Code that handles an IOException // This code can use the "ioex" variable to reference the exception } catch (Exception ex) { // Code that handles any other exception } Additional examples of exceptions appear throughout the book, beginning in section 2.3.2 on page 58. A.4.2 A RRAYS An array is a data structure consisting of a collection of variables, all of the same type. Arrays are built into C# and may be one-dimensional or many-dimensional. Each dimension of an array has an associated integral length. Arrays are treated as reference types. In the .NET Framework, the System.Array class serves as the base class for all array objects. More information on the Array and related ArrayList class can be found in chapter 5. A standard array for any type is constructed using square brackets in the following manner: <type> [ <dimension> opt ] where • <type> is the non-array type for the array. A non-array type is any type that is not an array. • <dimension> is zero or more commas ‘,’ indicating the dimensions of the array. Note that multiple square brackets may be specified to have variable length array ele- ments. An example of this is shown below. To reference a value in an array, square brackets are again used, with an integer expression from zero (0) to one less than the length of the array. If an array index is outside of the valid range of the array, an IndexOutOfRangeException object is thrown as an exception. Some examples of arrays and additional comments on the use of arrays are given below. Note that the Length property from the System.Array class determines the number of elements in an array, and the foreach keyword can be used on all arrays to enumerate the elements of the array. // an uninitialized array defaults to null int[] a; SPECIAL FEATURES 671 // This array contains 4 int values, which default to 0 // Here, the valid indexes are b[0], b[1], b[2], b[3] int[] b = new int[4]; // An array can be initialized directly or with the new keyword // evens.Length will return 6 // foreach (int p in primes) iterates through the elements in primes int[] evens = { 2, 4, 6, 8, 10, 12 }; int[] primes = new int[] {2, 3, 5, 7, 11, 101, 9876543211 }; // This example shows a 2 by 2 string array // Here, names[0,0] = "Katie" and names[1,1] = "Bianca" string[,] names = { { "Katie", "Sydney" }, { "Edmund", "Bianca"} }; // This example shows an array of arrays. // Here, x[0] is an int array of length three with values 1, 2, 3. // Also, x[1][1] = 12 and x[2][4] = 25. // Attempting to reference x[3] or x[1][2] will throw an exception int[][] x = { { 1, 2, 3 }, { 11, 12 }, { 21, 22, 23, 24, 25} }; A.4.3 MAIN A program has to start somewhere. In C and C++ programs, the global procedure main is the defined entry point for the program. This starting point is referred to as the entry point for the program. In C#, a class must define a static method called Main to serve as the entry point. The method must have one of the following signatures. static void Main() static void Main(string[] args) static int Main() static int Main(string[] args) A program will return a value if the Main method returns a value. A program can receive command-line arguments by specifying an array of string objects as the only parameter to the Main method. If two or more classes in a program contain a Main method, then the /main switch must be used with the C# compiler to specify which method to consider the entry point for the program. A.4.4 B OXING By definition, the object class is a reference type. However, it also serves as the ulti- mate base class for all types, including the built-in types. As a result, value types such as int and bool can be used wherever an object instance is required. For example, the ArrayList class represents a dynamically-sized array, and includes an Add method to add an object to the array. This method is declared as follows: public virtual int Add(object value); 672 APPENDIX A C# PRIMER Within the Add method, a reference type is expected. So what happens when a value type is passed into this method? Clearly, an explicit mechanism for treating value types as a reference type is required. This mechanism is called boxing. Boxing implicitly copies the data in a value type into an object instance allocated on the heap. For example: // Boxing of an integer constant object obj = 123; // Boxing of an int type. ArrayList list = new ArrayList(); int x = 32768; list.Add(x); A boxed value is converted back into a value type through a process called unboxing. Conceptually, boxing and unboxing happens automatically and the programmer can remain blissfully unaware of this concept. Boxed values can be treated as their unboxed equivalents. For example: int n = 5; object obj = 123; if (obj is int) n = (int) obj; These statements are perfectly legal, and result in the value of 123 for the variable n. The reason boxing is important is because of the performance implications involved. The boxing and unboxing of values takes time, and this can seriously impact the per- formance of an application. Note in particular that boxing occurs when a structure, which is a value type, is cast to an interface, which is a reference type. For this reason, care should be taken when creating structures that support one or more interfaces. In such a situation, the performance implications of boxing might warrant using a class instead of a structure. A.4.5 D OCUMENTATION A final topic worth mentioning in this appendix is that of automated documentation. C# supports a set of XML-style tags that can be used in comments and extracted by the compiler. Such comments must begin with a triple-slash ( ///) and can occur before the declaration of most types and type members. The C# compiler supports the /doc switch to generate the XML documentation file. Details on this process and the resulting output are available in the .NET docu- mentation. SPECIAL FEATURES 673 The following table provides a summary of the tags that are currently recognized by the compiler. An example using the <summary> tag appears in section 5.2.1 on page 134. C# documentation tags Tag Purpose <c> Specifies text that should be marked as code. <code> Specifies multiple lines that should be marked as code. <example> Documents an example of a type or method. <exception> Specifies documentation for an exception class. <include> Includes an external file to include in the documentation. <list> Specifies a list of items within another tag. This supports bulleted lists, numbered lists, and tables. <para> Starts a new paragraph within another tag. <param> Documents a parameter within a method or other construct. <paramref> Specifies text that should be marked as a parameter. <permission> Documents the accessibility level of a member. <remarks> Documents general comments about a type or type member. <returns> Documents the return value of a method. <see> Specifies a link in running text to another member or field accessible from the current file. <seealso> Specifies a link in a See Also section to another member of field accessible form the current file. <summary> Documents a short description of the member or type. <value> Documents a short description of a property. 674 APPENDIX B .NET namespaces B.1 System.Collections 675 B.2 System.ComponentModel 675 B.3 System.Data 675 B.4 System.Drawing 675 B.5 System.Globalization 676 B.6 System.IO 676 B.7 System.Net 676 B.8 System.Reflection 677 B.9 System.Resources 677 B.10 System.Security 678 B.11 System.Threading 678 B.12 System.Web 679 B.13 System.Windows.Forms 679 B.14 System.XML 679 This appendix provides an overview of some of the System namespaces provided by Microsoft in the .NET Framework, and discusses their relationship to Windows Forms applications. For a complete list of namespaces in .NET, see the .NET Frame- work Class Library documentation. The System namespace contains the commonly-used types 1 required by .NET programs and libraries, as well as services such as data type conversion, environment management, and mathematical operations. In particular, most of the classes men- tioned in Appendix A that implement core functionality such as the built-in types, enumerations, and delegates are included in this namespace. Members of this namespace are discussed throughout the book as they are used in the sample programs. 1 The word type is used in the C# sense here, as defined in Appendix A. More generally, a type can be a class, structure, interface, enumeration, or a delegate. By definition, a namespace defines one or more types. SYSTEM.DRAWING 675 The remainder of this appendix discusses specific namespaces under the System umbrella. Each section discusses a separate namespace, with the sections arranged in alphabetical order. For additional information on these and other namespaces in .NET, see the resources listed in Appendix D and in the bibliography. For some sample applications along with a discussion of many of these namespaces, see the book Microsoft .NET for Programmers by Fergal Grimes, available from Manning Publications. B.1 SYSTEM.COLLECTIONS The System.Collections namespace defines various types required to manipu- late collections of objects, including lists, queues, stacks, hash tables, and dictionaries. An exception is the Array class, which is part of the System namespace, since this class provides core functionality defined by the C# language. Members of this namespace are discussed throughout the book, and in particular in chapter 5, where the PhotoAlbum class is built as a collection of Photograph objects. B.2 SYSTEM.COMPONENTMODEL This namespace defines various types that define the runtime and design-time behav- ior of components and controls. In particular, this class defines the Component and Container classes and their corresponding interfaces. The Component class is introduced in chapter 3 as the base class for much of the functionality in the Windows Forms namespace. Members of this namespace are also critical for data binding support, which is discussed in chapter 17. B.3 SYSTEM.DATA The System.Data namespace defines classes and other types that constitute the ADO.NET architecture. This architecture enables the manipulation and manage- ment of data from multiple data sources, including both local and remote databases and connected or disconnected interaction. Although this namespace is not discussed in detail in the book, chapter 17 pro- vides some details on using databases with the data binding interface supported by Windows Forms, and in particular with the Windows.Forms.DataGrid control. See the bibliography for references to additional information on this namespace, and in particular the book ADO.NET Programming by Arlen Feldman, available from Manning Publications. B.4 SYSTEM.DRAWING This namespace defines basic functionality in the GDI, or graphical device interface, architecture. This includes the Graphics class for drawing to a device, as well as the Pen class for drawing lines and curves and the Brush class used to fill the interiors of [...]... functionality required by Windows Forms applications This figure shows the complete set of Windows Forms classes derived from the System .Windows. Forms. CommonDialog class COMMON DIALOGS 685 C.5 CONTROLS (PART 1) Figure C.5 The Windows Forms Control class represents a component with a visual representation on the Windows desktop This and the following figure show the complete set of Windows Forms classes derived... System .Windows. Forms. Control class 686 A P P EN D I X C VISUAL INDEX C.6 CONTROLS (PART 2) Figure C.6 The Windows Forms Control class represents a component with a visual representation on the Windows desktop This and the preceding figure show the complete set of Windows Forms classes derived from the System .Windows. Forms. Control class CONTROLS (PART 2) 687 C.7 EVENT DATA This table shows the Windows Forms. .. The related System .Windows. Forms. Design namespace is used to provide design-time support for Windows Forms controls, most notably for integrating custom controls into Visual Studio NET The design namespace permits custom controls to define their behavior in the Toolbox and Properties windows, and manage their appearance when displayed in the Windows Forms Designer window The Windows Forms namespace is,... interfaces in Web applications As this book is all about building Windows- based applications, it does not discuss these namespaces See the references listed in appendix D and the bibliography for more information on building Web applications and services B.13 SYSTEM .WINDOWS. FORMS The System .Windows. Forms namespace defines types for building Windowsbased applications The Control class in this namespace... classes The related System.Net.Sockets namespace defines a managed implementation of the Windows Sockets interface These interfaces can be very useful in Windows Forms applications for interacting with remote servers and services, and for building custom communication interfaces between one or more applications In Windows Forms applications, it is common to create a specific thread responsible for external... microsoft.public.dotnet.framework.windowsforms microsoft.public.dotnet.languages.csharp 691 bibliography Microsoft NET Framework Archor, Tom Inside C#, Redmond, WA: Microsoft Press, 2001 Cabanski, Tom .NET Security Greenwich, CT: Manning Publications Co., 2002 Conrad, James, et al Introducing NET Birmingham, UK: Wrox Press, 2001 Dennis, Alan .NET Multithreading, Greenwich, CT: Manning Publications Co., 2002 Feldman, Arlen ADO.NET Programming, ... appendix 680 The figures and tables on subsequent pages have the following features: • Classes in the Windows Forms namespace are gray • Classes from other namespaces are white • Classes presented or discussed in the book provide the corresponding table or section and page number The complete set of all Windows Forms classes derived from the MarshalByRefObject, Component, and Control classes are provided... marshaled by reference This figure shows the complete set of Windows Forms classes derived from the System.MarshalByRefObject class MARSHAL BY REFERENCE OBJECTS 683 C.3 COMPONENTS Figure C.3 The Component class represents an object that is marshaled by reference and can exist within a container This figure shows the complete set of Windows Forms classes derived from the System.ComponentModel.Component... memory, databases, or other shared data at the same time As we focused on the Windows Forms namespace in this book, our examples did not include multiple threads of control For a detailed discussion of how threads are used in NET applications, including Windows- based programs, see NET Multithreading by Alan Dennis, available from Manning Publications 678 A PP E ND I X B NET NAMESPACES B.12 SYSTEM.WEB This... numbers A number of Windows Forms controls include some sort of formatting property that can be used to specify formatting information Chapter 11 discusses the DataTimeFormatInfo class defined in this namespace, and the MonthCalendar control that relies on the calendar information maintained by classes within this namespace Chapter 17 also introduces the Format event in the Windows. Forms. Binding class . information on building Web applications and services. B.13 SYSTEM .WINDOWS. FORMS The System .Windows. Forms namespace defines types for building Windows- based applications. The Control class in this namespace. their behavior in the Toolbox and Properties windows, and manage their appearance when displayed in the Windows Forms Designer window. The Windows Forms namespace is, of course, the topic of this. for common functionality required by Windows Forms applications. This figure shows the complete set of Windows Forms classes derived from the System.Win- dows .Forms. CommonDialog class.

Ngày đăng: 07/07/2014, 04:20