System.Windows.Shapes.Rectangle与System.Drawing.Rectangle的区别

rax405 2009-09-23 10:10:08
System.Windows.Shapes.Rectangle与System.Drawing.Rectangle的区别是什么呢,我知道前者是要.Net 3.x环境才可以支持的,需不需用户自己绘制呢。
小弟我没分了,先谢过了。
...全文
249 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
rax405 2009-09-24
  • 打赏
  • 举报
回复
谢谢
Dobzhansky 2009-09-23
  • 打赏
  • 举报
回复
强 type,

都是几个数字的封装, 强 type 也好玩也不好玩
About this manual 13 Using this manual..14 Accessing ActionScript documentation15 ActionScript learning resources.. 17 Chapter 1: Introduction to ActionScript 3.0.. 19 About ActionScript..19 Advantages of ActionScript 3.0.20 What’s new in ActionScript 3.0.. 21 Core language features...21 Flash Player API features...23 Compatibility with previous versions24 Chapter 2: Getting started with ActionScript..27 Programming fundamentals27 What computer programs do..27 Variables and constants...28 Data types...29 Working with objects.. 31 Properties...31 Methods32 Events33 Basic event handling...34 Examining the event-handling process... 35 Event-handling examples.. 39 Creating object instances...40 Common program elements..42 Example: Animation portfolio piece44 Building applications with ActionScript.47 Options for organizing your code48 Choosing the right tool...50 The ActionScript development process 51 Creating your own classes...53 Strategies for designing a class. 53 Writing the code for a class..54 4 Suggestions for organizing your classes...56 Example: Creating a basic application 56 Running subsequent examples.. 63 Chapter 3: ActionScript language and syntax.67 Language overview..68 Objects and classes.69 Packages and namespaces... 70 Packages...70 Namespaces..75 Variables83 Data types87 Type checking..88 Dynamic classes..93 Data type descriptions94 Type conversions.97 Syntax 103 Operators 109 Conditionals...117 Looping119 Functions 122 Basic function concepts... 122 Function parameters 128 Functions as objects 134 Function scope.135 Chapter 4: Object-oriented programming in ActionScript.137 Basics of object-oriented programming 138 Classes140 Class definitions..141 Class property attributes... 144 Variables...147 Methods...148 Enumerations with classes..156 Embedded asset classes...158 Interfaces 158 Inheritance162 Advanced topics..171 Example: GeometricShapes..180 5 Chapter 5: Working with dates and times... 191 Basics of dates and times191 Managing calendar dates and times193 Controlling time intervals196 Example: Simple analog clock...199 Chapter 6: Working with strings203 Basics of strings.. 204 Creating strings... 205 The length property. 207 Working with characters in strings208 Comparing strings.208 Obtaining string representations of other objects.209 Concatenating strings209 Finding substrings and patterns in strings210 Converting strings between uppercase and lowercase215 Example: ASCII art..216 Chapter 7: Working with arrays223 Basics of arrays... 223 Indexed arrays...225 Associative arrays.234 Multidimensional arrays...239 Cloning arrays...241 Advanced topics..241 Example: PlayList..247 Chapter 8: Handling errors. 253 Basics of error handling...254 Types of errors..257 Error handling in ActionScript 3.0259 ActionScript 3.0 error-handling elements..260 Error-handling strategies...261 Working with the debugger version of Flash Player.261 Handling synchronous errors in an application.. 262 Creating custom error classes.. 267 Responding to error events and status268 6 Comparing the Error classes...272 ECMAScript core Error classes..272 ActionScript core Error classes.275 flash.error package Error classes276 Example: CustomErrors application278 Chapter 9: Using regular expressions...285 Basics of regular expressions..286 Regular expression syntax288 Creating an instance of a regular expression..289 Characters, metacharacters, and metasequences 290 Character classes.293 Quantifiers..295 Alternation...297 Groups297 Flags and properties. 301 Methods for using regular expressions with strings.305 Example: A Wiki parser...306 Chapter 10: Handling events313 Basics of handling events...314 How ActionScript 3.0 event handling differs from earlier versions317 The event flow..320 Event objects...322 Event listeners...327 Example: Alarm Clock335 Chapter 11: Working with XML343 Basics of XML..344 The E4X approach to XML processing348 XML objects... 350 XMLList objects...353 Initializing XML variables354 Assembling and transforming XML objects356 Traversing XML structures...358 Using XML namespaces363 XML type conversion.364 Reading external XML documents.366 Example: Loading RSS data from the Internet..367 7 Chapter 12: Display programming371 Basics of display programming.372 Core display classes377 Advantages of the display list approach 379 Working with display objects..382 Properties and methods of the DisplayObject class...382 Adding display objects to the display list... 383 Working with display object containers...383 Traversing the display list..387 Setting Stage properties..389 Handling events for display objects392 Choosing a DisplayObject subclass393 Manipulating display objects..395 Changing position395 Panning and scrolling display objects 400 Manipulating size and scaling objects402 Controlling distortion when scaling 403 Caching display objects... 405 When to enable caching.. 406 Enabling bitmap caching.. 408 Setting an opaque background color...409 Applying blending modes...409 Adjusting DisplayObject colors..410 Setting color values with code411 Altering color and brightness effects with code.412 Rotating objects..413 Fading objects..413 Masking display objects...414 Animating objects...416 Loading display content dynamically418 Loading display objects...419 Monitoring loading progress.420 Specifying loading context..421 Example: SpriteArranger...423 Chapter 13: Working with geometry431 Basics of geometry.431 Using Point objects. 434 Using Rectangle objects436 Using Matrix objects440 Example: Applying a matrix transformation to a display object.442 8 Chapter 14: Using the drawing API...447 Basics of using the drawing API..448 Understanding the Graphics class450 Drawing lines and curves...450 Drawing shapes using built-in methods453 Creating gradient lines and fills..454 Using the Math class with drawing methods..460 Animating with the drawing API.461 Example: Algorithmic Visual Generator462 Chapter 15: Filtering display objects...465 Basics of filtering display objects..465 Creating and applying filters...467 Creating a new filter467 Applying a filter..467 How filters work..470 Potential issues for working with filters470 Available display filters472 Bevel filter473 Blur filter474 Drop shadow filter..474 Glow filter...475 Gradient bevel filter.476 Gradient glow filter477 Example: Combining basic filters478 Color matrix filter. 480 Convolution filter.481 Displacement map filter484 Example: Filter Workbench...490 Chapter 16: Working with movie clips 491 Basics of movie clips491 Working with MovieClip objects.. 494 Controlling movie clip playback.494 Working with scenes497 Creating MovieClip objects with ActionScript.. 498 Exporting library symbols for ActionScript..498 Loading an external SWF file..501 Example: RuntimeAssetsExplorer503 9 Chapter 17: Working with text 509 Basics of working with text510 Displaying text513 Types of text...513 Modifying the text field contents.514 Displaying HTML text514 Using images in text fields...515 Scrolling text in a text field...516 Selecting and manipulating text..517 Capturing text input.518 Restricting text input520 Formatting text..520 Assigning text formats521 Applying cascading style sheets..521 Loading an external CSS file..523 Formatting ranges of text within a text field... 524 Advanced text rendering525 Working with static text528 Example: Newspaper-style text formatting... 529 Reading the external CSS file.530 Arranging story elements on the page...532 Altering font size to fit the field size533 Splitting text across multiple columns535 Chapter 18: Working with bitmaps539 Basics of working with bitmaps..540 The Bitmap and BitmapData classes543 Manipulating pixels.. 545 Manipulating individual pixels.545 Pixel-level collision detection.547 Copying bitmap data549 Making textures with noise functions550 Scrolling bitmaps.552 Example: Animating sprites using an offscreen bitmap...553 Chapter 19: Working with video555 Basics of video..556 Understanding the Flash Video (FLV) format..559 Understanding the Video class.560 Loading video files..561 Controlling video playback... 562 Detecting the end of a video stream563 10 Streaming video files.564 Understanding cue points...565 Writing callback methods for onCuePoint and onMetaData..566 Set the NetStream object’s client property to an Object...567 Create a custom class and define methods to handle the callback methods.568 Extend the NetStream class and add methods to handle the callback methods569 Extend the NetStream class and make it dynamic570 Set the NetStream object’s client property to this.572 Using cue points..572 Using video metadata.573 Capturing camera input 577 Understanding the Camera class577 Displaying camera content on-screen578 Designing your camera application.578 Connecting to a user’s camera..578 Verifying that cameras are installed.579 Detecting permissions for camera access..580 Maximizing video quality...582 Monitoring playback conditions..583 Sending video to a server...584 Advanced topics..585 Flash Player compatibility with encoded FLV files585 About configuring FLV files for hosting on a server585 About targeting local FLV files on the Macintosh.586 Example: Video Jukebox587 Chapter 20: Working with sound 595 Basics of working with sound.. 596 Understanding the sound architecture599 Loading external sound files..600 Working with embedded sounds. 603 Working with streaming sound files 604 Playing sounds..605 Pausing and resuming a sound606 Monitoring playback.607 Stopping streaming sounds.609 Security considerations when loading and playing sounds..609 Controlling sound volume and panning.611 Working with sound metadata.. 613 Accessing raw sound data 614 Capturing sound input617 11 Accessing a microphone... 617 Routing microphone audio to local speakers...619 Altering microphone audio...619 Detecting microphone activity. 620 Sending audio to and from a media server621 Example: Podcast Player...622 Reading RSS data for a podcast channel..623 Simplifying sound loading and playback using the SoundFacade class.623 Displaying playback progress.627 Pausing and resuming playback.628 Extending the Podcast Player example...629 Chapter 21: Capturing user input.631 Basics of user input.631 Capturing keyboard input...633 Capturing mouse input 636 Example: WordSearch641 Chapter 22: Networking and communication645 Basics of networking and communication...646 Working with external data...649 Connecting to other Flash Player instances...656 Socket connections. 662 Storing local data.668 Working with file upload and download671 Example: Building a Telnet client. 682 Example: Uploading and downloading files... 685 Chapter 23: Client system environment..695 Basics of the client system environment695 Using the System class 698 Using the Capabilities class..699 Using the ApplicationDomain class700 Using the IME class. 704 Example: Detecting system capabilities 709 12 Chapter 24: Printing... 715 Basics of printing..716 Printing a page..718 Flash Player tasks and system printing719 Setting size, scale, and orientation.722 Example: Multiple-page printing.725 Example: Scaling, cropping, and responding..727 Chapter 25: Using the external API...731 Basics of using the external API..732 External API requirements and advantages...735 Using the ExternalInterface class..736 Getting information about the external container737 Calling external code from ActionScript...737 Calling ActionScript code from the container...739 The external API’s XML format.740 Example: Using the external API with a web page container..742 Example: Using the external API with an ActiveX container..749 Chapter 26: Flash Player security757 Flash Player security overview..758 Overview of permission controls.760 Security sandboxes.. 770 Restricting networking APIs..773 Full-screen mode security...775 Loading content... 776 Cross-scripting...779 Accessing loaded media as data.783 Loading data786 Loading embedded content from SWF files imported into a security domain..788 Working with legacy content..789 Setting LocalConnection permissions.790 Controlling access to scripts in a host web page..790 Shared objects...792 Camera, microphone, clipboard, mouse, and keyboard access.794
Table of Contents Preface Preface Prerequisites Conventions Resources Acknowledgments 2. The GTK+/GNOME System GLib Simple Data Types Namespaces Logging Containers Other Toys GDK The GTK+ Connection The Thin Wrapper GDK Events Drawing Primitives Reference Counting GTK+ Widgets The GTK+ Type System Object Classes Object Properties Signals GNOME Core Libraries Graphics Libraries Components Gnome-xml 3. The GNOME Build Environment The Configuration Script Running configure Inside the configure Script Makefile Variable Substitution Creating Your Own Configuration Autoconf The Configuration Header Checking for Tools Checking for Header Files Custom Checks Helper Tools Generating Makefiles GNU Makefile Standards Using automake Automake Variables Conditional Compiling Cutting a Distribution Dealing with Libraries Libtool Support libtoolize A Grumpy Example Exploring the Results A Note about Version Numbers Adding GNOME GNOME Macros gnome-config GNOME Makefile Variables autogen.sh Some Grumpy GNOME Examples 10. Graphics Graphics in the X Window System Frame Buffers Color Maps Visuals Drawables Images The GDK Wrapper Simpler API Using Color in GDK GdkRGB The RGB Buffer Drawing Functions Color Management Libart Vector Paths Bezier Paths Sorted Vector Paths Microtile Arrays Affine Transformations Pixel Buffers Gdk-pixbuf Creating Rendering Scaling Progressive Loading Autoconf Support Gdk-pixbuf Application Example 11. The GNOME Canvas The Canvas Double-Buffered Drawing Surface The Canvas Abstraction Canvas Groups Events Coordinate Systems World Coordinates Item Coordinates Canvas Coordinates Window Coordinates Using the Canvas GDK versus AA The Scrolling Region Adding Canvas Items Moving Canvas Items Around Transformations Canvas Items Vector-Based Drawing Items Line Styles The Shape of the Item Widgets in the Canvas Text Canvas Items Graphical Canvas Items Canvas Events The Event Callback Clicks and Double Clicks Mouse Motion Rollovers Keyboard Events Grabbing Items Dragging and Dropping Canvas Items A. GNU Free Documentation License 0. PREAMBLE 1. APPLICABILITY AND DEFINITIONS 2. VERBATIM COPYING 3. COPYING IN QUANTITY 4. MODIFICATIONS 5. COMBINING DOCUMENTS 6. COLLECTIONS OF DOCUMENTS 7. AGGREGATION WITH INDEPENDENT WORKS 8. TRANSLATION 9. TERMINATION 10. FUTURE REVISIONS OF THIS LICENSE Addendum List of Figures 2-1. Singly and Doubly Linked Lists 2-2. Structure of a Hash Table 2-3. Structure of an N-ary Tree 2-4. The GNOME Dependency Tree 2-5. GDK Event Flow 2-6. Widget Appearances 3-1. Running the configure Script 3-2. Running aclocal 3-3. Four Grumpy Library Cases 10-1. Color Map Example 10-2. Relationships among X Visuals 10-3. Double Buffering with a Pixmap 10-4. RGB Row Strides 10-5. Array of ArtVpath Elements 10-6. Vector Paths of the Letters V and R 10-7. Microtile Arrays 10-8. Rendering an Alpha Channel to a Bitmap 10-9. Scaling Parameters 10-10. Image Composition with testpixbuf-scale 10-11. Screen Shot of Sample Gdk-pixbuf Application 11-1. The test-gnome Application 11-2. Maximizing the Viewing Space 11-3. Bitmaps for Stipple Masks 11-4. Stipple Mask Example 11-5. Arrow Shapes for GnomeCanvasLine Item 11-6. Rectangle and Ellipse Canvas Items with the Same Bounding Box
Preface 1 Chapter 1: Start your Engines 5 Introduction 5 Running a shortest Python program 6 Ensuring that the Python modules are present 7 A basic Tkinter program 9 Make a compiled executable under Windows and Linux 11 Chapter 2: Drawing Fundamental Shapes 15 Introduction 16 A straight line and the coordinate system 17 Draw a dashed line 18 Lines of varying styles with arrows and endcaps 20 A two segment line with a sharp bend 22 A line with a curved bend 23 Drawing intricate shapes – the curly vine 24 Draw a rectangle 27 Draw overlapping rectangles 28 Draw concentric squares 30 A circle from an oval 32 A circle from an arc 34 Three arc ellipses 35 Polygons 36 A star polygon 37 Cloning and resizing stars 39 Chapter 3: Handling Text 43 Introduction 43 Simple text 43 ii Table of Contents Text font type, size, and color 45 Alignment of text – left and right justify 49 All the fonts available on your computer 54 Chapter 4: Animation Principles 57 Introduction 57 Static shifting of a ball 58 Time-controlled shifting of a ball 59 Complete animation using draw-move-pause-erase cycles 62 More than one moving object 63 A ball that bounces 65 Bouncing in a gravity field 67 Precise collisions using floating point numbers 70 Trajectory tracing and ball-to-ball collisions 72 Rotating line 76 Trajectory tracing on multiple line rotations 78 A rose for you 82 Chapter 5: The Magic of Color 85 Introduction 85 A limited palette of named colors 86 Nine ways of specifying color 90 A red beachball of varying hue 91 A red color wedge of graded hue 94 Newton's grand wheel of color mixing 96 The numerical color mixing matching palette 101 The animated graded color wheel 106 Tkinter's own color picker-mixer 110 Chapter 6: Working with Pictures 113 Opening an image file and discovering its attributes 114 Open, view, and save an image in a different file format 117 Image format conversion for JPEG, PNG, TIFF, GIF, BMP 118 Image rotation in the plane of the image 120 Image size alteration 121 Correct proportion image resizing 123 Separating one color band in an image 124 Red, green, and blue color alteration in images 125 Slider controlled color manipulation 127 Combining images by blending 130 Blending images by varying percentages 131 Make a composite image using a mask image 132 iii Table of Contents Offset (roll) image horizontally and vertically 134 Flip horizontally, vertically, and rotate 134 Filter effects: blur, sharpen, contrast, and so on 135 Chapter 7: Combining Raster and Vector Pictures 139 Simple animation of a GIF beach ball 140 The vector walking creature 141 Bird with shoes walking in the Karroo 145 Making GIF images with transparent backgrounds using GIMP 149 Diplomat walking at the palace 152 Spider in the forest 156 Moving band of images 160 Continuous band of images 162 Endless background 164 Chapter 8: Data In and Data Out 167 Introduction 167 Creation of a new file on a hard drive 168 Writing data to a newly-created file 169 Writing data to multiple files 169 Adding data to existing files 170 Saving a Tkinter-drawing shape to disk 171 Retrieving Python data from disk storage 172 Simple mouse input 173 Storing and retrieving a mouse-drawn shape 174 A mouse-line editor 177 All possible mouse actions 181 Chapter 9: Exchanging Inkscape SVG Drawings with Tkinter Shapes 185 Introduction 185 The structure of an SVG drawing 186 Tracing the shape of an image in Inkscape 189 Converting an SVG path into a Tkinter Line 194 Chapter 10: GUI Construction: Part 1 199 Introduction 199 Widget configuration – a label 200 Button focus 201 The simplest push button with validation 203 A data entry box 204 Colored button causing a message pop-up 207 Complex interaction between buttons 208 Images on buttons and button packing 211 iv Table of Contents Grid Geometry Manager and button arrays 213 Drop-down menus to select from a list 215 Listbox variable selection 216 Text in a window 218 Chapter 11: GUI Construction: Part 2 219 Introduction 219 The Grid Layout Geometry Manager 220 The Pack Geometry Manager 222 Radiobuttons to select one from many 223 Checkbuttons (Tickboxes) to select some of many 224 Key-stroke event handling 226 Scrollbar 227 Custom DIY controller widgets 228 Organizing widgets inside frames 232 Appendix: Quick tips for running Python programs in Microsoft Windows 235 Running Python programs in Microsoft Windows 235 Where will we find the windows installer? 235 Do we have to use Python version 2.7? 236 Why do we get "python is not recognized…"? 236 Index 239 Preface Python 2.6 Graphics Cookbook is a collection of straightforward recipes and illustrative screenshots for creating and animating graphic objects using the Python language. This book makes the process of developing graphics interesting and entertaining by working in a graphic workspace, without the burden of mastering complicated language definitions and opaque examples. What this book covers Chapter 1, Start your Engines: This chapter explains how to acquire and install the Python interpreter, for MS Windows or Linux as well as how to verify that Python is correctly installed. This chapter explains how to create complete working programs that can be run on client computers that do not have Python installed. Chapter 2, Drawing Fundamental Shapes: This shows how to create all the fundamental graphic elements including lines, circles, ovals, rectangles, polygons, and complex curves. Simple examples are provided to demonstrate how to draw the elementary shapes. The examples also provide a ready for reference for later use. Chapter 3, Handling Text: This chapter demonstrates how to control font size, color, and position using any of the font typefaces installed on the specific operating system being used. A simple means of discovering and demonstrating all available fonts on the operating system is shown. Chapter 4, Animation Principles: This chapter starts with examples of simple sequences of a circle in different positions and systematically progresses to smoothly-moving animations of elastic balls bouncing inside a gravity field. Chapter 5, The Magic of Color: This chapter begins with the assembling of color palettes using color names recognizable to Python. The way colors are constructed using numbers to mix controlled amounts of red, green, and blue is explained. Tools for matching colors to any sample are constructed. This chapter demonstrates how to vary shadings of one color into another. Download from Wow! eBook Preface Chapter 6, Working with Pictures: This chapter reveals how to acquire and use the Python Imaging Library to manipulate photo images. It also shows methods of image format conversion, re-sizing, rotating, color transforming, and complex filtering. Chapter 7, Combining Vector and Raster Images: This chapter demonstrates the ways of combining animated vector graphics with photographic images to produce complex animations. Chapter 8, Data in and Data Out: This chapter starts with basic storing and retrieving of files to a hard drive and progresses to the construction of programs that are tools for creating, storing, and retrieving free-form shapes drawn using a mouse. Chapter 9, Exchanging Inkscape SVG Drawings with Tkinter Shapes: This chapter shows in detail how to use the Inkscape drawing tool to convert shapes traced from a photographic image into a sequence of points which reproduce the shape in Python. Once a line is expressed as a Python sequence, it can be transformed numerically in many ways. Chapter 10, GUI Construction: Part 1: This chapter provides basic examples of how to create buttons, data entry boxes, drop-down menus, list-boxes, and text labels. It also covers how to customize button appearance. Chapter 11, GUI Construction: Part 2: Here the Grid Layout Manager and the Pack Layout Manager are explained and demonstrated. Examples of radio buttons, check buttons, scrollbars, frames, and keystroke event coding are given. It also shows how to construct widgets using graphic elements on a canvas. Appendix, Quick tips for running Python programs in Microsoft Windows: This gives explanations of how to overcome some of the difficulties a new python programmer might encounter when trying to use Python in Windows. What you need for this book To run the code in this book, the reader will need a Linux operating system or Microsoft Windows, and some way of downloading Python, the Python Imaging Library, and Inkscape from the internet. All these applications are free and open source. The code has been developed on Linux Ubuntu version 9.04, Microsoft Windows XP, and Windows 7. Who this book is for This book is for Python programmers wanting simple, clear examples of graphic programming using Python. The examples are aimed at anyone wanting to use graphic elements and images inside Python programs with the minimum of complexity. The intended reader ranges from scholars and teachers to engineers and technicians
是英文的,全面包含了c#的各方面。是非常好的一本书,绝对值得下载。 Introduction xxvii Part I: The C# Language 1 Chapter 1: .NET Architecture 3 The Relationship of C# to .NET 4 The Common Language Runtime 4 Advantages of Managed Code 4 A Closer Look at Intermediate Language 7 Support for Object Orientation and Interfaces 8 Distinct Value and Reference Types 9 Strong Data Typing 9 Error Handling with Exceptions 16 Use of Attributes 17 Assemblies 17 Private Assemblies 18 Shared Assemblies 19 Reflection 19 .NET Framework Classes 19 Namespaces 21 Creating .NET Applications Using C# 21 Creating ASP.NET Applications 21 Creating Windows Forms 24 Windows Services 24 The Role of C# in the .NET Enterprise Architecture 24 Summary 26 Chapter 2: C# Basics 29 Before We Start 30 Our First C# Program 30 The Code 30 Compiling and Running the Program 31 Contents A Closer Look 31 Variables 34 Initialization of Variables 34 Variable Scope 35 Constants 38 Predefined Data Types 39 Value Types and Reference Types 39 CTS Types 40 Predefined Value Types 41 Predefined Reference Types 44 Flow Control 47 Conditional Statements 47 Loops 51 Jump Statements 54 Enumerations 55 Arrays 57 Namespaces 58 The using Statement 59 Namespace Aliases 60 The Main() Method 61 Multiple Main() Methods 61 Passing Arguments to Main() 62 More on Compiling C# Files 63 Console I/O 65 Using Comments 67 Internal Comments Within the Source Files 67 XML Documentation 68 The C# Preprocessor Directives 70 #define and #undef 70 #if, #elif, #else, and #endif 71 #warning and #error 72 #region and #endregion 72 #line 72 C# Programming Guidelines 73 Rules for Identifiers 73 Usage Conventions 74 Summary 81 Chapter 3: Objects and Types 83 Classes and Structs 84 Class Members 85 Data Members 85 Function Members 85 xi Contents readonly Fields 99 Structs 101 Structs Are Value Types 102 Structs and Inheritance 103 Constructors for Structs 103 The Object Class 104 System.Object Methods 104 The ToString() Method 105 Summary 107 Chapter 4: Inheritance 109 Types of Inheritance 109 Implementation Versus Interface Inheritance 109 Multiple Inheritance 110 Structs and Classes 110 Implementation Inheritance 111 Virtual Methods 112 Hiding Methods 113 Calling Base Versions of Functions 114 Abstract Classes and Functions 115 Sealed Classes and Methods 115 Constructors of Derived Classes 116 Modifiers 122 Visibility Modifiers 122 Other Modifiers 123 Interfaces 123 Defining and Implementing Interfaces 125 Derived Interfaces 128 Summary 130 Chapter 5: Operators and Casts 131 Operators 131 Operator Shortcuts 133 The Ternary Operator 134 The checked and unchecked Operators 134 The is Operator 135 The as Operator 136 The sizeof Operator 136 The typeof Operator 136 Contents Operator Precedence 137 Type Safety 137 Type Conversions 138 Boxing and Unboxing 141 Comparing Objects for Equality 142 Comparing Reference Types for Equality 142 The ReferenceEquals() Method 142 The virtual Equals() Method 143 The static Equals() Method 143 Comparison Operator (==) 143 Comparing Value Types for Equality 143 Operator Overloading 144 How Operators Work 145 Operator Overloading Example: The Vector Struct 146 Which Operators Can You Overload? 153 User-Defined Casts 154 Implementing User-Defined Casts 155 Multiple Casting 161 Summary 165 Chapter 6: Delegates and Events 167 Delegates 167 Using Delegates in C# 169 SimpleDelegate Example 172 BubbleSorter Example 174 Multicast Delegates 177 Events 179 The Receiver’s View of Events 180 Generating Events 182 Summary 186 Chapter 7: Memory Management and Pointers 187 Memory Management under the Hood 187 Value Data Types 188 Reference Data Types 190 Garbage Collection 192 Freeing Unmanaged Resources 193 Destructors 193 The IDisposable Interface 195 xiii Contents Implementing IDisposable and a Destructor 196 Unsafe Code 197 Pointers 198 Pointer Example: PointerPlayaround 207 Using Pointers to Optimize Performance 212 Summary 216 Chapter 8: Strings and Regular Expressions 217 System.String 218 Building Strings 219 Format Strings 223 Regular Expressions 229 Introduction to Regular Expressions 229 The RegularExpressionsPlayaround Example 230 Displaying Results 233 Matches, Groups, and Captures 234 Summary 237 Chapter 9: Collections 239 Examining Groups of Objects 239 Array Lists 240 Collections 241 Dictionaries 245 Summary 256 Chapter 10: Reflection 257 Custom Attributes 258 Writing Custom Attributes 258 Custom Attribute Example: WhatsNewAttributes 262 Reflection 265 The System.Type Class 266 The TypeView Example 268 The Assembly Class 271 Completing the WhatsNewAttributes Sample 272 Summary 276 Contents Chapter 11: Errors and Exceptions 277 Looking into Errors and Exception Handling 277 Exception Classes 278 Catching Exceptions 280 User-Defined Exception Classes 290 Summary 297 Part II: The .NET Environment 299 Chapter 12: Visual Studio .NET 301 Working with Visual Studio .NET 2003 301 Creating a Project 304 Solutions and Projects 311 Windows Application Code 314 Reading in Visual Studio 6 Projects 314 Exploring and Coding a Project 315 Building a Project 326 Debugging 331 Other .NET Tools 334 The ASP.NET Web Matrix Project 335 WinCV 335 Summary 337 Chapter 13: Assemblies 339 What Are Assemblies? 339 The Answer to DLL Hell 340 Features of Assemblies 341 Application Domains and Assemblies 341 Assembly Structure 344 Assembly Manifests 346 Namespaces, Assemblies, and Components 346 Private and Shared Assemblies 347 Viewing Assemblies 347 Building Assemblies 348 Cross-Language Support 353 The CTS and the CLS 353 Language Independence in Action 354 CLS Requirements 364 xv Contents Global Assembly Cache 366 Native Image Generator 366 Global Assembly Cache Viewer 367 Global Assembly Cache Utility (gacutil.exe) 368 Creating Shared Assemblies 369 Shared Assembly Names 369 Creating a Shared Assembly 371 Configuration 376 Configuration Categories 376 Versioning 377 Configuring Directories 387 Summary 390 Chapter 14: .NET Security 391 Code Access Security 392 Code Groups 393 Code Access Permissions and Permissions Sets 399 Policy Levels: Machine, User, and Enterprise 403 Support for Security in the Framework 405 Demanding Permissions 406 Requesting Permissions 407 Implicit Permission 410 Denying Permissions 411 Asserting Permissions 412 Creating Code Access Permissions 414 Declarative Security 414 Role-Based Security 415 The Principal 415 Windows Principal 416 Roles 417 Declarative Role-Based Security 418 Managing Security Policy 419 The Security Configuration File 419 Managing Code Groups and Permissions 423 Turning Security On and Off 423 Resetting Security Policy 423 Creating a Code Group 423 Deleting a Code Group 424 Changing a Code Group’s Permissions 424 Creating and Applying Permissions Sets 425 Distributing Code Using a Strong Name 427 Contents Distributing Code Using Certificates 429 Managing Zones 435 Summary 437 Chapter 15: Threading 439 Threading 439 Applications with Multiple Threads 441 Manipulating Threads 441 The ThreadPlayaround Sample 444 Thread Priorities 448 Synchronization 449 Summary 453 Chapter 16: Distributed Applications with .NET Remoting 455 What Is .NET Remoting? 456 Application Types and Protocols 456 CLR Object Remoting 457 .NET Remoting Overview 457 Contexts 460 Activation 461 Attributes and Properties 461 Communication between Contexts 462 Remote Objects, Clients, and Servers 462 Remote Objects 462 A Simple Server 464 A Simple Client 465 .NET Remoting Architecture 466 Channels 466 Formatters 470 ChannelServices and RemotingConfiguration 471 Object Activation 472 Message Sinks 476 Passing Objects in Remote Methods 476 Lifetime Management 481 Miscellaneous .NET Remoting Features 484 Configuration Files 484 Hosting Applications 494 Classes, Interfaces, and SoapSuds 495 Asynchronous Remoting 498 Remoting and Events 499 Call Contexts 505 Summary 507 xvii Contents Chapter 17: Localization 509 Namespace System.Globalization 510 Unicode Issues 510 Cultures and Regions 511 Cultures in Action 516 Sorting 520 Resources 522 Creating Resource Files 522 ResGen 523 ResourceWriter 523 Using Resource Files 524 The System.Resources Namespace 527 Localization Example Using Visual Studio .NET 527 Outsourcing Translations 533 Changing the Culture Programmatically 534 Using Binary Resource Files 536 Using XML Resource Files 537 Automatic Fallback for Resources 539 Globalization and Localization with ASP.NET 539 A Custom Resource Reader 540 Creating a DatabaseResourceReader 541 Creating a DatabaseResourceSet 542 Creating a DatabaseResourceManager 543 Client Application for DatabaseResourceReader 544 Summary 544 Chapter 18: Deployment 545 Designing for Deployment 545 Deployment Options 546 Xcopy 546 Copy Project 546 Deployment Projects 546 Deployment Requirements 546 Simple Deployment 547 Xcopy 548 Xcopy and Web Applications 548 Copy Project 550 Installer Projects 551 What Is Windows Installer? 551 Creating Installers 552 Advanced Options 562 Summary 569 Contents Part III: Windows Forms 571 Chapter 19: Windows Forms 573 Creating a Windows Form Application 574 Control Class 579 Size and Location 580 Appearance 580 User Interaction 580 Windows Functionality 582 Miscellaneous Functionality 582 Class Hierarchy 582 Standard Controls and Components 584 Forms 598 Form Class 599 Multiple Document Interface (MDI) 607 Custom Controls 610 Summary 622 Chapter 20: Graphics with GDI+ 623 Understanding Drawing Principles 624 GDI and GDI+ 624 Drawing Shapes 626 Painting Shapes Using OnPaint() 629 Using the Clipping Region 630 Measuring Coordinates and Areas 632 Point and PointF 632 Size and SizeF 634 Rectangle and RectangleF 635 Region 636 A Note about Debugging 637 Drawing Scrollable Windows 638 World, Page, and Device Coordinates 644 Colors 645 Red-Green-Blue (RGB) Values 645 The Named Colors 646 Graphics Display Modes and the Safety Palette 646 The Safety Palette 647 Pens and Brushes 648 Brushes 648 Pens 649 xix Contents Drawing Shapes and Lines 650 Displaying Images 652 Issues When Manipulating Images 655 Drawing Text 655 Simple Text Example 656 Fonts and Font Families 657 Example: Enumerating Font Families 659 Editing a Text Document: The CapsEditor Sample 661 The Invalidate() Method 666 Calculating Item Sizes and Document Size 667 OnPaint() 668 Coordinate Transforms 670 Responding to User Input 671 Printing 675 Implementing Print and Print Preview 676 Summary 680 Part IV: Data 683 Chapter 21: Data Access with .NET 685 ADO.NET Overview 685 Namespaces 686 Shared Classes 686 Database-Specific Classes 687 Using Database Connections 688 Using Connections Efficiently 689 Transactions 692 Commands 693 Executing Commands 694 Calling Stored Procedures 698 Fast Data Access: The Data Reader 701 Managing Data and Relationships: The DataSet Class 704 Data Tables 704 Data Columns 705 Data Relationships 711 Data Constraints 713 XML Schemas 715 Generating Code with XSD 716 Populating a DataSet 721 Populating a DataSet Class with a Data Adapter 722 Populating a DataSet from XML 723 xx Contents Persisting DataSet Changes 723 Updating with Data Adapters 724 Writing XML Output 726 Working with ADO.NET 728 Tiered Development 728 Key Generation with SQL Server 730 Naming Conventions 732 Summary 734 Chapter 22: Viewing .NET Data 735 The DataGrid Control 735 Displaying Tabular Data 735 Data Sources 738 DataGrid Class Hierarchy 746 Data Binding 750 Simple Binding 750 Data-Binding Objects 751 Visual Studio.NET and Data Access 757 Creating a Connection 758 Selecting Data 759 Generating a DataSet 762 Updating the Data Source 763 Building a Schema 764 Other Common Requirements 770 Summary 778 Chapter 23: Manipulating XML 781 XML Standards Support in .NET 782 Introducing the System.Xml Namespace 782 Using MSXML in .NET 783 Using System.Xml Classes 786 Reading and Writing Streamed XML 786 Using the XmlTextReader Class 787 Using the XmlValidatingReader Class 791 Using the XmlTextWriter Class 794 Using the DOM in .NET 795 Using the XmlDocument Class 797 Using XPath and XSLT in .NET 802 The System.Xml.XPath Namespace 803 The System.Xml.Xsl Namespace 807 Contents XML and ADO.NET 812 Converting ADO.NET Data to XML 812 Converting XML to ADO.NET Data 820 Reading and Writing a DiffGram 822 Serializing Objects in XML 825 Serialization without Source Code Access 833 Summary 836 Chapter 24: Working with Active Directory 837 The Architecture of Active Directory 838 Features 838 Active Directory Concepts 839 Characteristics of Active Directory Data 843 Schema 843 Administration Tools for Active Directory 845 Active Directory Users and Computers 845 ADSI Edit 846 Active Directory Service Interfaces (ADSI) 847 Programming Active Directory 848 Classes in System.DirectoryServices 849 Binding 849 Getting Directory Entries 854 Object Collections 855 Cache 857 Creating New Objects 857 Updating Directory Entries 858 Accessing Native ADSI Objects 859 Searching in Active Directory 860 Searching for User Objects 864 User Interface 864 Get the Schema Naming Context 864 Get the Property Names of the User Class 866 Search for User Objects 867 Summary 869 Part V: Web Programming 871 Chapter 25: ASP.NET Pages 873 ASP.NET Introduction 874 State Management in ASP.NET 875 xxii Contents ASP.NET Web Forms 875 ASP.NET Server Controls 880 ADO.NET and Data Binding 892 Updating the Event-Booking Application 893 More on Data Binding 901 Application Configuration 906 Summary 907 Chapter 26: Web Services 909 SOAP 910 WSDL 911 Web Services 913 Exposing Web Services 913 Consuming Web Services 916 Extending the Event-Booking Example 918 The Event-Booking Web Service 919 The Event-Booking Client 922 Exchanging Data Using SOAP Headers 924 Summary 929 Chapter 27: User Controls and Custom Controls 931 User Controls 932 A Simple User Control 932 Custom Controls 939 Custom Control Project Configuration 940 Basic Custom Controls 944 Creating a Composite Custom Control 949 A Straw Poll Control 951 The Candidate Controls 953 The StrawPoll Control Builder 954 Straw Poll Style 955 The Straw Poll Control 956 Summary 962 Part VI: Interop 963 Chapter 28: COM Interoperability 965 .NET and COM 966 Metadata 966 Freeing Memory 966 xxiii Contents Interfaces 967 Method Binding 969 Data Types 969 Registration 969 Threading 969 Error Handling 971 Event Handling 972 Marshaling 972 Using a COM Component from a .NET Client 973 Creating a COM Component 973 Creating a Runtime Callable Wrapper 977 Threading Issues 980 Adding Connection Points 980 Using ActiveX Controls in Windows Forms 982 Using COM Objects from within ASP.NET 985 Using a .NET Component from a COM Client 985 COM Callable Wrapper 986 Creating a .NET Component 986 Creating a Type Library 987 COM Interop Attributes 989 COM Registration 992 Creating a COM Client 993 Adding Connection Points 995 Creating a Client with a Sink Object 996 Running Windows Forms Controls in Internet Explorer 997 Summary 998 Chapter 29: Enterprise Services 999 Overview 999 History 999 Where to Use Enterprise Services? 1000 Contexts 1001 Automatic Transactions 1001 Distributed Transactions 1001 Object Pooling 1002 Role-based Security 1002 Queued Components 1002 Loosely Coupled Events 1002 Creating a Simple COM+ Application 1003 Class ServicedComponent 1003 Application Attributes 1003 Creating the Component 1004 Contents Deployment 1005 Automatic Deployment 1005 Manual Deployment 1005 Component Services Admin Tool 1006 Client Application 1008 Transactions 1009 ACID Properties 1009 Transaction Attributes 1009 Transaction Results 1010 Sample Application 1011 Summary 1021 Part VII: Windows Base Services 1023 Chapter 30: File and Registry Operations 1025 Managing the File System 1026 .NET Classes That Represent Files and Folders 1027 The Path Class 1029 Example: A File Browser 1030 Moving, Copying, and Deleting Files 1035 Example: FilePropertiesAndMovement 1035 Reading and Writing to Files 1039 Streams 1040 Reading and Writing to Binary Files 1042 Reading and Writing to Text Files 1047 Reading and Writing to the Registry 1054 The Registry 1055 The .NET Registry Classes 1057 Example: SelfPlacingWindow 1059 Summary 1066 Chapter 31: Accessing the Internet 1067 The WebClient Class 1068 Downloading Files 1068 Basic Web Client Example 1068 Uploading Files 1070 WebRequest and WebResponse Classes 1070 Other WebRequest and WebResponse Features 1071 Displaying Output as an HTML Page 1074 The Web Request and Web Response Hierarchy 1075 xxv Contents Utility Classes 1077 URIs 1077 IP Addresses and DNS Names 1079 Lower-Level Protocols 1082 Lower-Level Classes 1083 Summary 1088 Chapter 32: Windows Services 1091 What Is a Windows Service? 1091 Windows Services Architecture 1093 Service Program 1093 Service Control Program 1095 Service Configuration Program 1095 System.ServiceProcess Namespace 1095 Creating a Windows Service 1096 A Class Library Using Sockets 1096 TcpClient Example 1100 Windows Service Project 1102 Threading and Services 1107 Service Installation 1107 Installation Program 1108 Monitoring and Controlling the Service 1113 MMC Computer Management 1114 net.exe 1114 sc.exe 1115 Visual Studio .NET Server Explorer 1116 ServiceController Class 1116 Troubleshooting 1122 Interactive Services 1123 Event Logging 1123 Performance Monitoring 1130 Power Events 1135 Summary 1135 At www.wrox.com Appendix A: Principles of Object-Oriented Programming 1137 Appendix B: C# for Visual Basic 6 Developers 1177 Appendix C: C# for Java Developers 1225 Appendix D: C# for C++ Developers 1253 Index 1307
在一小时内学会 C#。使用例程,简单却完整的探索 C# 语言的构造和特点。本文特别适合有 C++ 基础却没有太多精力学习 C# 的读者。 关于作者 Aisha Ikram 我现在在英国一家软件公司任技术带头人。我是计算机科学的硕士。我主要使用 .NET 1.1/2.0, C#, VB.NET, ASP.NET, VC++ 6, MFC, ATL, COM/DCOM, SQL Server 2000/2005等。最近我在学习 .NET 3.x 的全部内容。我的免费源代码和文章网站是 http://aishai.netfirms.com 职业:团队带头人 位置:英国 简介 C# 是一种具有 C++ 特性,Java 样式及 BASIC 快速建模特性的编程语言。如果你已经知晓 C++ 语言,本文将在不到一小时的时间内带你快速浏览 C# 的语法。如果熟悉 Java 语言,Java 的编程结构、打包和垃圾回收的概念肯定对你快速学习 C# 大有帮助。所以我在讨论 C# 语言构造的时候会假设你知道 C++。 本文通过一系列例程以简短但全面的方式讨论了 C# 语言构造和特性,所以你仅需略览代码片刻,即可了解其概念。 注意:本文不是为 C# 宗师而写。有很多初学者的 C# 文章,这只是其中之一。 接下来关于 C# 的讨论主题: ? 编程结构 ? 命名空间 ? 数据类型 ? 变量 ? 运算符与表达式 ? 枚举 ? 语句 ? 类与结构 ? 修饰符 ? 属性 ? 接口 ? 函数参数 ? 数组 ? 索引器 ? 装箱与拆箱 ? 委托 ? 继承与多态 以下主题不会进行讨论: ? C++ 与 C# 的共同点 ? 诸如垃圾回收、线程、文件处理等概念 ? 数据类型转换 ? 异常处理 ? .NET 库 编程结构 和 C++ 一样,C# 是大小写敏感的。半角分号(;)是语句分隔符。和 C++ 有所区别的是,C# 中没有单独的声明(头)和实现(CPP)文件。所有代码(类声明和实现)都放在扩展名为 cs 的单一文件中。 看看 C# 中的 Hello World 程序。 复制内容到剪贴板 代码: using System; namespace MyNameSpace { class HelloWorld { static void Main(string[] args) { Console.WriteLine ("Hello World"); } } } C# 中所有内容都打包在类中,而所有的类又打包在命名空间中(正如文件存与文件夹中)。和 C++ 一样,有一个主函数作为你程序的入口点。C++ 的主函数名为 main,而 C# 中是大写 M 打头的 Main。 类块或结构定义之后没有必要再加一个半角分号。C++ 中是这样,但 C# 不要求。 命名空间 每个类都打包于一个命名空间。命名空间的概念和 C++ 完全一样,但我们在 C# 中比在 C++ 中更加频繁的使用命名空间。你可以用点(.)定界符访问命名空间中的类。上面的 Hello World 程序中,MyNameSpace 是其命名空间。 现在思考当你要从其他命名空间的类中访问 HelloWorld 类。 复制内容到剪贴板 代码: using System; namespace AnotherNameSpace { class AnotherClass { public void Func() { Console.WriteLine ("Hello World"); } } } 现在在你的 HelloWorld 类中你可以这样访问: 复制内容到剪贴板 代码: using System; using AnotherNameSpace; // 你可以增加这条语句 namespace MyNameSpace { class HelloWorld { static void Main(string[] args) { AnotherClass obj = new AnotherClass(); obj.Func(); } } } 在 .NET 库中,System 是包含其他命名空间的顶层命名空间。默认情况下存在一个全局命名空间,所以在命名空间外定义的类直接进到此全局命名空间中,因而你可以不用定界符访问此类。 你同样可以定义嵌套命名空间。 Using #include 指示符被后跟命名空间名的 using 关键字代替了。正如上面的 using System。System 是最基层的命名空间,所有其他命名空间和类都包含于其中。System 命名空间中所有对象的基类是 Object。 变量 除了以下差异,C# 中的变量几乎和 C++ 中一样: 1. C# 中(不同于 C++)的变量,总是需要你在访问它们前先进行初始化,否则你将遇到编译时错误。故而,不可能访问未初始化的变量。 2. 你不能在 C# 中访问一个“挂起”指针。 3. 超出数组边界的表达式索引值同样不可访问。 4. C# 中没有全局变量或全局函数,取而代之的是通过静态函数和静态变量完成的。 数据类型 所有 C# 的类型都是从 object 类继承的。有两种数据类型: 1. 基本/内建类型 2. 用户定义类型 以下是 C# 内建类型的列表: 类型 字节 描述 byte 1 unsigned byte sbyte 1 signed byte short 2 signed short ushort 2 unsigned short int 4 signed integer uint 4 unsigned integer long 8 signed long ulong 8 unsigned long float 4 floating point number double 8 double precision number decimal 8 fixed precision number string - Unicode string char - Unicode char bool true, false boolean 注意:C# 的类型范围和 C++ 不同。例如:long 在 C++ 中是 4 字节而在 C# 中是 8 字节。bool 和 string 类型均和 C++ 不同。bool 仅接受真、假而非任意整数。 用户定义类型文件包含: 1. 类 (class) 2. 结构(struct) 3. 接口(interface) 以下类型继承时均分配内存: 1. 值类型 2. 参考类型 值类型 值类型是在堆栈中分配的数据类型。它们包括了: ? 除字符串,所有基本和内建类型 ? 结构 ? 枚举类型 引用类型 引用类型在堆(heap)中分配内存且当其不再使用时,将自动进行垃圾清理。和 C++ 要求用户显示创建 delete 运算符不一样,它们使用新运算符创建,且没有 delete 运算符。在 C# 中它们自动由垃圾回收系统回收。 引用类型包括: ? 类 ? 接口 ? 集合类型如数组 ? 字符串 枚举 C# 中的枚举和 C++ 完全一样。通过关键字 enum 定义。 例子: 复制内容到剪贴板 代码: enum Weekdays { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday } 类与结构 除了内存分配的不同外,类和结构就和 C++ 中的情况一样。类的对象在堆中分配,并使用 new 关键字创建。而结构是在栈(stack)中进行分配。C# 中的结构属于轻量级快速数据类型。当需要大型数据类型时,你应该创建类。 例子: 复制内容到剪贴板 代码: struct Date { int day; int month; int year; } class Date { int day; int month; int year; string weekday; string monthName; public int GetDay() { return day; } public int GetMonth() { return month; } public int GetYear() { return year; } public void SetDay(int Day) { day = Day ; } public void SetMonth(int Month) { month = Month; } public void SetYear(int Year) { year = Year; } public bool IsLeapYear() { return (year/4 == 0); } public void SetDate (int day, int month, int year) { } ... } 属性 如果你熟悉 C++ 面向对象的方法,你一定对属性有自己的认识。对 C++ 来说,前面例子中 Date 类的属性就是 day、month 和 year,而你添加了 Get 和 Set 方法。C# 提供了一种更加便捷、简单而又直接的属性访问方式。 所以上面的类应该写成这样: 复制内容到剪贴板 代码: using System; class Date { public int Day{ get { return day; } set { day = value; } } int day; public int Month{ get { return month; } set { month = value; } } int month; public int Year{ get { return year; } set { year = value; } } int year; public bool IsLeapYear(int year) { return year%4== 0 ? true: false; } public void SetDate (int day, int month, int year) { this.day = day; this.month = month; this.year = year; } } 这里是你 get 和 set 属性的方法: 复制内容到剪贴板 代码: class User { public static void Main() { Date date = new Date(); date.Day = 27; date.Month = 6; date.Year = 2003; Console.WriteLine ("Date: {0}/{1}/{2}", date.Day, date.Month, date.Year); } } 修饰符 你必须知道 C++ 中常用的 public、private 和 protected 修饰符。我将在这里讨论一些 C# 引入的新的修饰符。 readonly readonly 修饰符仅用于修饰类的数据成员。正如其名字说的,一旦它们已经进行了写操作、直接初始化或在构造函数中对其进行了赋值,readonly 数据成员就只能对其进行读取。readonly 和 const 数据成员不同之处在于 const 要求你在声明时进行直接初始化。看下面的例程: 复制内容到剪贴板 代码: class MyClass { const int constInt = 100; //直接进行 readonly int myInt = 5; //直接进行 readonly int myInt2; public MyClass() { myInt2 = 8; //间接进行 } public Func() { myInt = 7; //非法 Console.WriteLine(myInt2.ToString()); } } sealed 带有 sealed 修饰符的类不允许你从它继承任何类。所以如果你不想一个类被继承,你可以对该类使用 sealed 关键字。 复制内容到剪贴板 代码: sealed class CanNotbeTheParent { int a = 5; } unsafe 你可以使用 unsafe 修饰符在 C# 中定义一个不安全上下文。在不安全上下文中,你可以插入不安全代码,如 C++ 的指针等。参见以下代码: 复制内容到剪贴板 代码: public unsafe MyFunction( int * pInt, double* pDouble) { int* pAnotherInt = new int; *pAnotherInt = 10; pInt = pAnotherInt; ... *pDouble = 8.9; } 接口 如果你有 COM 的思想,你马上就知道我在说什么了。接口是只包含函数签名而在子类中实现的抽象基类。在 C# 中,你可以用 interface 关键字声明这样的接口类。.NET 就是基于这样的接口的。C# 中你不能对类进行多重继承——这在 C++ 中是允许的。通过接口,多重继承的精髓得以实现。即你的子类可以实现多重接口。(译注:由此可以实现多重继承) 复制内容到剪贴板 代码: using System; interface myDrawing { int originx { get; set; } int originy { get; set; } void Draw(object shape); } class Shape: myDrawing { int OriX; int OriY; public int originx { get{ return OriX; } set{ OriX = value; } } public int originy { get{ return OriY; } set{ OriY = value; } } public void Draw(object shape) { ... // 做要做的事 } // 类自身的方法 public void MoveShape(int newX, int newY) { ..... } } 数组 数组在 C# 中比 C++ 中要高级很多。数组分配于堆中,所以是引用类型的。你不能访问数组边界外的元素。所以 C# 防止你引发那种 bug。同时也提供了迭代数组元素的帮助函数。foreach 是这样的迭代语句之一。C++ 和 C# 数组的语法差异在于: 方括号在类型后面而不是在变量名后面 创建元素使用 new 运算符 C# 支持一维、多维和交错数组(数组的数组) 例子: 复制内容到剪贴板 代码: int[] array = new int[10]; // int 型一维数组 for (int i = 0; i < array.Length; i++) array = i; int[,] array2 = new int[5,10]; // int 型二维数组 array2[1,2] = 5; int[,,] array3 = new int[5,10,5]; // int 型三维数组 array3[0,2,4] = 9; int[][] arrayOfarray = new int[2]; // int 型交错数组 - 数组的数组 arrayOfarray[0] = new int[4]; arrayOfarray[0] = new int[] {1,2,15}; 索引器 索引器用于书写一个可以通过使用 [] 像数组一样直接访问集合元素的方法。你所需要的只是指定待访问实例或元素的索引。索引器的语法和类属性语法相同,除了接受作为元素索引的输入参数外。 例子: 注意:CollectionBase 是用于建立集合的库类。List 是 CollectionBase 中用于存放集合列表的受保护成员。 复制内容到剪贴板 代码: class Shapes: CollectionBase { public void add(Shape shp) { List.Add(shp); } //indexer public Shape this[int index] { get { return (Shape) List[index]; } set { List[index] = value ; } } } 装箱/拆箱 装箱的思想在 C# 中是创新的。正如前面提到的,所有的数据类型,无论是内建的还是用户定义的,都是从 System 命名空间的基类 object 继承的。所以基础的或是原始的类型打包为一个对象称为装箱,相反的处理称为拆箱。 例子: 复制内容到剪贴板 代码: class Test { static void Main() { int myInt = 12; object obj = myInt ; // 装箱 int myInt2 = (int) obj; // 拆箱 } } 例程展示了装箱和拆箱两个过程。一个 int 值可以被转换为对象,并且能够再次转换回 int。当某种值类型的变量需要被转换为一个引用类型时,便会产生一个对象箱保存该值。拆箱则完全相反。当某个对象箱被转换回其原值类型时,该值从箱中拷贝至适当的存储空间。 函数参数 C# 中的参数有三种类型: 1. 按值传递/输入参数 2. 按引用传递/输入-输出参数 3. 输出参数 如果你有 COM 接口的思想,而且还是参数类型的,你会很容易理解 C# 的参数类型。 按值传递/输入参数 值参数的概念和 C++ 中一样。传递的值复制到了新的地方并传递给函数。 例子: 复制内容到剪贴板 代码: SetDay(5); ... void SetDay(int day) { .... } 按引用传递/输入-输出参数 C++ 中的引用参数是通过指针或引用运算符 & 传递的。C# 中的引用参数更不易出错。你可以传递一个引用地址,你传递一个输入的值并通过函数得到一个输出的值。因此引用参数也被称为输入-输出参数。 你不能将未初始化的引用参数传递给函数。C# 使用关键字 ref 指定引用参数。你同时还必须在传递参数给要求引用参数的函数时使用关键字 ref。 例子: 复制内容到剪贴板 代码: int a= 5; FunctionA(ref a); // 使用 ref,否则将引发编译时错误 Console.WriteLine(a); // 打印 20 复制内容到剪贴板 代码: void FunctionA(ref int Val) { int x= Val; Val = x* 4; } 输出参数 输出参数是只从函数返回值的参数。输入值不要求。C# 使用关键字 out 表示输出参数。 例子: 复制内容到剪贴板 代码: int Val; GetNodeValue(Val); 复制内容到剪贴板 代码: bool GetNodeValue(out int Val) { Val = value; return true; } 参数和数组的数量变化 C# 中的数组使用关键字 params 进行传递。一个数组类型的参数必须总是函数最右边的参数。只有一个参数可以是数组类型。你可以传送任意数量的元素作为数组类型的参数。看了下面的例子你可以更好的理解: 注意:使用数组是 C# 提供用于可选或可变数量参数的唯一途径。 例子: 复制内容到剪贴板 代码: void Func(params int[] array) { Console.WriteLine("number of elements {0}", array.Length); } 复制内容到剪贴板 代码: Func(); // 打印 0 Func(5); // 打印 1 Func(7,9); // 打印 2 Func(new int[] {3,8,10}); // 打印 3 int[] array = new int[8] {1,3,4,5,5,6,7,5}; Func(array); // 打印 8 运算符与表达式 运算符和表达式跟 C++ 中完全一致。然而同时也添加了一些新的有用的运算符。有些在这里进行了讨论。 is 运算符 is 运算符是用于检查操作数类型是否相等或可以转换。is 运算符特别适合用于多态的情形。is 运算符使用两个操作数,其结果是布尔值。参考例子: 复制内容到剪贴板 代码: void function(object param) { if(param is ClassA) //做要做的事 else if(param is MyStruct) //做要做的事 } } as 运算符 as 运算符检查操作数的类型是否可转换或是相等(as 是由 is 运算符完成的),如果是,则处理结果是已转换或已装箱的对象(如果操作数可以装箱为目标类型,参考 装箱/拆箱)。如果对象不是可转换的或可装箱的,返回值为 null。看看下面的例子以更好的理解这个概念。 复制内容到剪贴板 代码: Shape shp = new Shape(); Vehicle veh = shp as Vehicle; // 返回 null,类型不可转换 Circle cir = new Circle(); Shape shp = cir; Circle cir2 = shp as Circle; //将进行转换 object[] objects = new object[2]; objects[0] = "Aisha"; object[1] = new Shape(); string str; for(int i=0; i&< objects.Length; i++) { str = objects as string; if(str == null) Console.WriteLine("can not be converted"); else Console.WriteLine("{0}",str); } 复制内容到剪贴板 代码: Output: Aisha can not be converted 语句 除了些许附加的新语句和修改外,C# 的语句和 C++ 的基本一致。 以下是新的语句: foreach 用于迭代数组等集合。 例子: 复制内容到剪贴板 代码: foreach (string s in array) Console.WriteLine(s); lock 在线程中使代码块称为重点部分。 (译注:lock 关键字将语句块标记为临界区,方法是获取给定对象的互斥锁,执行语句,然后释放该锁。lock 确保当一个线程位于代码的临界区时,另一个线程不进入临界区。如果其他线程试图进入锁定的代码,则它将一直等待(即被阻止),直到该对象被释放。) checked/unchecked 用于数字操作中的溢出检查。 例子: 复制内容到剪贴板 代码: int x = Int32.MaxValue; x++; // 溢出检查 { x++; // 异常 } unchecked { x++; // 溢出 } 下面的语句已修改:(译注:原文如此,疑为作者笔误) Switch Switch 语句在 C# 中修改过。 1.现在在执行一条 case 语句后,程序流不能跳至下一 case 语句。之前在 C++ 中这是可以的。 例子: 复制内容到剪贴板 代码: int var = 100; switch (var) { case 100: Console.WriteLine(""); // 这里没有 break case 200: Console.WriteLine(""); break; } C++ 的输出: 复制内容到剪贴板 代码: 而在 C# 中你将得到一个编译时错误: 复制内容到剪贴板 代码: error CS0163: Control cannot fall through from one case label ('case 100:') to another 2.然而你可以像在 C++ 中一样这么用: 复制内容到剪贴板 代码: switch (var) { case 100: case 200: Console.WriteLine("100 or 200"); break; } 3.你还可以用常数变量作为 case 值: 例子: 复制内容到剪贴板 代码: const string WeekEnd = "Sunday"; const string WeekDay1 = "Monday"; .... string WeekDay = Console.ReadLine(); switch (WeekDay ) { case WeekEnd: Console.WriteLine("It's weekend!!"); break; case WeekDay1: Console.WriteLine("It's Monday"); break; } 委托 委托让我们可以把函数引用保存在变量中。这就像在 C++ 中使用 typedef 保存函数指针一样。 委托使用关键字 delegate 声明。看看这个例子,你就能理解什么是委托: 例子: 复制内容到剪贴板 代码: delegate int Operation(int val1, int val2); public int Add(int val1, int val2) { return val1 + val2; } public int Subtract (int val1, int val2) { return val1- val2; } public void Perform() { Operation Oper; Console.WriteLine("Enter + or - "); string optor = Console.ReadLine(); Console.WriteLine("Enter 2 operands"); string opnd1 = Console.ReadLine(); string opnd2 = Console.ReadLine(); int val1 = Convert.ToInt32 (opnd1); int val2 = Convert.ToInt32 (opnd2); if (optor == "+") Oper = new Operation(Add); else Oper = new Operation(Subtract); Console.WriteLine(" Result = {0}", Oper(val1, val2)); } 继承与多态 C# 只允许单一继承。多重继承可以通过接口达到。 例子: 复制内容到剪贴板 代码: class Parent{ } class Child : Parent 虚函数 虚函数在 C# 中同样是用于实现多态的概念的,除了你要使用 override 关键字在子类中实现虚函数外。父类使用同样的 virtual 关键字。每个重写虚函数的类都使用 override 关键字。(译注:作者所说的“同样”,“除……外”都是针对 C# 和 C++ 而言的) 复制内容到剪贴板 代码: class Shape { public virtual void Draw() { Console.WriteLine("Shape.Draw") ; } } class Rectangle : Shape { public override void Draw() { Console.WriteLine("Rectangle.Draw"); } } class Square : Rectangle { public override void Draw() { Console.WriteLine("Square.Draw"); } } class MainClass { static void Main(string[] args) { Shape[] shp = new Shape[3]; Rectangle rect = new Rectangle(); shp[0] = new Shape(); shp[1] = rect; shp[2] = new Square(); shp[0].Draw(); shp[1].Draw(); shp[2].Draw(); } } Output: Shape.Draw Rectangle.Draw Square.Draw 使用“new”隐藏父类函数 你可以隐藏基类中的函数而在子类中定义其新版本。关键字 new 用于声明新的版本。思考下面的例子,该例是上一例子的修改版本。注意输出,我用 关键字 new 替换了 Rectangle 类中的关键字 override。 复制内容到剪贴板 代码: class Shape { public virtual void Draw() { Console.WriteLine("Shape.Draw") ; } } class Rectangle : Shape { public new void Draw() { Console.WriteLine("Rectangle.Draw"); } } class Square : Rectangle { //这里不用 override public new void Draw() { Console.WriteLine("Square.Draw"); } } class MainClass { static void Main(string[] args) { Console.WriteLine("Using Polymorphism:"); Shape[] shp = new Shape[3]; Rectangle rect = new Rectangle(); shp[0] = new Shape(); shp[1] = rect; shp[2] = new Square(); shp[0].Draw(); shp[1].Draw(); shp[2].Draw(); Console.WriteLine("Using without Polymorphism:"); rect.Draw(); Square sqr = new Square(); sqr.Draw(); } } Output: Using Polymorphism Shape.Draw Shape.Draw Shape.Draw Using without Polymorphism: Rectangle.Draw Square.Draw 多态性认为 Rectangle 类的 Draw 方法是和 Shape 类的 Draw 方法不同的另一个方法,而不是认为是其多态实现。所以为了防止父类和子类间的命名冲突,我们只有使用 new 修饰符。 注意:你不能在一个类中使用一个方法的两个版本,一个用 new 修饰符,另一个用 override 或 virtual。就像在上面的例子中,我不能在 Rectangle 类中增加另一个名为 Draw 的方法,因为它是一个 virtual 或 override 的方法。同样在 Square 类中,我也不能重写 Shape 类的虚方法 Draw。 调用基类成员 如果子类的数据成员和基类中的有同样的名字,为了避免命名冲突,基类成员和函数使用 base 关键字进行访问。看看下面的例子,基类构造函数是如何调用的,而数据成员又是如何使用的。 复制内容到剪贴板 代码: public Child(int val) :base(val) { myVar = 5; base.myVar; } OR public Child(int val) { base(val); myVar = 5 ; base.myVar; } 前景展望 本文仅仅是作为 C# 语言的一个快速浏览,以便你可以熟悉该语言的一些特性。尽管我尝试用实例以一种简短而全面的方式讨论了 C# 几乎所有的主要概念,但我认为还是有很多内容需要增加和讨论的。 以后,我会增加更多的没有讨论过的命令和概念,包括事件等。我还想给初学者写一下怎么用 C# 进行 Windows 编程。 参考文献: 我们都知道的 MSDN Tom Archer 著,Inside C# Eric Gunnerson 著,A Programmer's Introduction to C# Karli Watson 著,Beginning C# O'Reilly(奥莱利出版),Programming C# 修改: 2003年6月12日:按引用传递/输入-输出参数一节中增加了 ref 关键字 2003年6月20日:为可选参数增加了一条注意事项,纠正了交错数组例子中赋值运算符的笔误 许可 本文及其任何关联的源代码和文件均以 The Code Project Open License (CPOL)执行。(译注:代码计划网站公开许可)

110,566

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧