Statistics
47
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2025-12-07

AuthorSmith, Benjamin [Smith, Benjamin]

No description

Tags
No tags
Publish Year: 2021
Language: 英文
File Format: PDF
File Size: 3.0 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
(This page has no text content)
C# Advanced Guide to Learn C# Programming Effectively
© Copyright 2020 - All rights reserved. The content contained within this book may not be reproduced, duplicated or transmitted without direct written permission from the author or the publisher. Under no circumstances will any blame or legal responsibility be held against the publisher, or author, for any damages, reparation, or monetary loss due to the information contained within this book, either directly or indirectly. Legal Notice: This book is copyright protected. It is only for personal use. You cannot amend, distribute, sell, use, quote or paraphrase any part, or the content within this book, without the consent of the author or publisher. Disclaimer Notice: Please note the information contained within this document is for educational and entertainment purposes only. All effort has been executed to present accurate, up to date, reliable, complete information. No warranties of any kind are declared or implied. Readers acknowledge that the author is not engaging in the rendering of legal, financial, medical or professional advice. The content within this book has been derived from various sources. Please consult a licensed professional before attempting any techniques outlined in this book. By reading this document, the reader agrees that under no circumstances is the author responsible for any losses, direct or indirect, that are incurred as a result of the use of information contained within this document, including, but not limited to, errors, omissions, or inaccuracies.
Table Of Contents Introduction Chapter 1: Getting Familiar with the Foundations of C# The Essentials of an Object-Oriented Programming Language Reflection Chapter 2: Working with the Assembly Viewer and UserControls Analyzing the Assembly Manager’s Code Listing Working with Windows Forms Control Multi-Threading using the ThreadPool Class Implementing a Control Library Creating a ButtonCluster Control Surfacing Constituent Events Creating a PickList Control Adding and Removing Elements BeginUpdate and EndUpdate Surfacing Constituent Properties Implementing the Class ‘ContactInformation’ Chapter 3: Working with Video Kiosk Using C# An Introduction to GDI+ An Introduction to GDI+ Programming Creating the Graphics for the PlayControl Interface Drawing Shapes and Filling Them Moving Graphics Objects on the Screen using Transforms Creating Shaped Forms, using the GraphicsPath Object Defining Clipping Regions Linear-scaling Gradient Bushes Tracker Control Secondary Topics
The Elapsed Time Clock Tooltip Control COM Interop Chapter 4: Personalizing the Visual Studio .NET Framework Environment Making a Wizard A Wizard Project Creating a Project Template for Visual Studio .NET Wizards Extending Visual Studio .NET with Wizards Writing a Macro Code Generator Implementing the Wizard UI Completing the Sample Wizard Launch File Secondary Topics Conclusion
Introduction Object-oriented programming is like a rabbit hole; once you start to explore it, the tunnel only seems to get deeper and deeper. This is especially true because of the family of programming languages whose cores are based on object-oriented techniques and principles. C++, C, Java, Javascript, PHP, Visual Basic, Microsoft .NET, Ruby, Scala, and a bunch of other programming languages are all classified as ‘OOPL’ (Object-Oriented Programming Languages). In this language family, C# is similar to that sibling who is difficult to get along with but incredibly resourceful. C# is alluring and fascinating to some people, while to others, it is a real hassle to learn and work with this language, but none of these two people at the opposite ends of the spectrum are to blame. People familiar with mainstream OOPL, such as C++, will find that C# has all those bells and whistles that you would find in other object-oriented languages, ultimately making it easier to learn C#, but even with these similarities, the implementation of the same techniques, tools, and concepts are radically different, and on top of that, C# does not have one defined IDE, anyway. At the same time, you can argue that no programming language has one IDE that’s better than the rest. Still, in the case of C#, the result is an inconsistency in the programming experience, not the case for other languages. Hence, trying to teach the reader a universal set of techniques and practices is quite literally impossible. Even the fundamental concepts may be different, even though you may be familiar with them from other object-oriented languages. For this very reason, the first chapter of the book is essentially a review of the most important programming concepts in C#. In this way, since all the readers will likely read this chapter before moving on, everyone will have the same idea of the concepts that are being explained and used in the upcoming chapters. This is very important because literally, every discussion being made after chapter 1 builds upon the concepts that are highlighted at the very beginning. Even if the reader already knows about all the concepts discussed in the first chapter, the chapter itself does not become useless because it
will still serve as an opportunity to review the knowledge that they already possess. If there’s something that is not clear or is ambiguously explained, then do a brief web-search. There’s a high chance that you might just need a small detail to understand what’s being discussed in the topic.
Chapter 1: Getting Familiar with the Foundations of C# This chapter will provide the reader with an overall review of the most important concepts in C sharp. This is necessary because the upcoming chapters will build upon the things we review here. This allows the readers to become familiar with the idioms commonly used in advanced C sharp programming (which will be quite frequently used in the upcoming chapters). In this way, this chapter hopes to get the readers on the same page before we move on with advanced programming techniques and projects in the latter half of this book. However, if you already have experience with object-oriented programming languages like Java, Javascript, C++, PHP, Visual Basic .NET, etc., you might think this chapter will probably not be worth your time, but this chapter will prove to be a really useful checkpoint where you can review the concepts you are already familiar with. On the other hand, most readers picking up this book will find this chapter to disclose certain aspects of not only C sharp but also .’NET’ programming that they were previously unaware of. In short, the content here will provide the readers with foundations necessary for understanding the discussion of C sharp programming to create advanced applications throughout the course of this book. The Essentials of an Object-Oriented Programming Language There is a set of fundamental elements that form the core of the language itself in any object-oriented programming language. These elements are generally known as the object-oriented basics, but this title is quite misleading as these “basics” are not to be underestimated. To be more precise, these basics are wrapped around with an external shell that gives the object-oriented language its unique identity. This is why C sharp, even though it is an object- oriented language like C++, Visual Basic, and Java, has its own unique way of distinguishing itself from its family members. In any object-oriented programming language, the underlying functioning principles remain the same. These principles are
essentially the “basics” of an object-oriented programming language, and they are a total of four. These basic principles are the following: 1. Encapsulation 2. Inheritance 3. Aggregation 4. Polymorphism As such, any programming language that incorporates these principles is categorized as an object-oriented programming language. In order to implement each of these principal elements properly within their cores, programming languages use tools known as ‘idioms ’ and ‘constructors .’ For instance, these include Templates Operator overloading Interfaces Multithreading Multiple Inheritance Exception handling Pointers Garbage collection, etc. When exploring C sharp, we find out that the core of this object- oriented programming language implements the principal elements with operator overloading, inheritance, interfaces, exception handling, garbage collection, multiple interface inheritance, reflection, and multi-threading, but you might notice that C sharp shuns a few functionalities such as templates, raw pointers, and even multiple class inheritance. The reason why these functionalities were not included within the C sharp programming language is because of the argument, which, on one side, supports the claim that these features introduce more problems than they can potentially solve. On the other side, the belief is that these are key components of any object-oriented programming language, and the features they bring to the table are priceless, and they need to be included, but keep things simple and straightforward, further complications were avoided by simply not adding these features to C sharp.
However, this does not give much confidence to anybody who has any experience in programming. This is because the feature set of templates, multiple inheritances, and pointers greatly facilitates the user in Web application and Web Services projects. Hence, this might be a monumental deal-breaker for some people, but C sharp does not disappoint their end-users. In order to make up for the lack of such tools, C sharp includes its own feature set that can help users to build Web Applications and Web Services. For instance, C sharp features a tool that allows for hosting applications on the Windows platform, namely, ‘COM interop .’ Not only that, but C sharp also boasts multilanguage programming as well as rapid application development. But through all this ramble, there is still good news. As we discussed before, all the object-oriented programming languages have the same core principles with a difference in the features implementing them. You will find that some features from other OOPLs carry on to C sharp. For instance, if you are comfortable with the syntax of C++ or Java, then you’ll find that the syntax of C sharp is strikingly familiar, thus allowing you to settle in considerably faster. This is just one of the many similarities you’ll find in C sharp when comparing it to other object-oriented programming languages, so it’s a good idea to make a quick comparison if you’re coming from such languages. In the upcoming sections, we will discuss the object-oriented basics and discuss the relative features available in C sharp. Defining Classes Creating and defining classes is done the same way as you would in C++, albeit the underlying construct of this action is slightly different in C sharp. The following syntax demonstrates the construct required to define a class in C sharp. Access-modifier class name { }
One thing to be mindful of is that just like C++, C sharp is a case- sensitive programming language. Thus, you need to be vigilant of the case in which your classes have been defined when referencing them. Otherwise, the compiler will not recognize which class you are referring to. The syntax demonstrated above has the potential of being confusing, so let’s clarify its elements. The syntax has two elements - the ‘access modifier ’ and the ‘name .’ The second element is self-explanatory, i.e., it is the set of characters by which the class is recognized, but the first element's purpose is to define the scope of the class (you should already be familiar with ‘scopes’). Generally, classes are specified as ‘public ’ (which is the same as ‘global ’ in other programming languages) so that they can be accessed by any function in any program, as long as the header file is included (where the classes have been already defined). So, if we replace the appropriate arguments in the syntax shown above, we will end up with something like this: public class MyFirstClass { } In the curly brackets, you fit in your class's contents (the functions, methods, and objects it includes). If you look a bit closer, you will see that the class's name has all the first letters of each word capitalized. This is not random or a mistake. Instead, we follow a convention here when naming classes. The purpose of a convention is to maintain consistency when programming, which can be really impactful in the long run, but it is not mandatory to follow this naming convention (known as ‘Pascal Casing’). It’s all up to you whether you choose to use it or not (the same goes for other numerous conventions in programming). Using a Class in a Console Application Assuming that you have some knowledge of programming or any amount of programming experience, then you must be familiar with
the term ‘console.’ When you are using IDE software to code, you will find a small window in the bottom that looks similar to that of a command prompt, giving the user feedback information when they execute certain commands (such as compile, debug, etc.). Moreover, a console will also display syntax errors in the code when asked to compile the project you have opened currently. Similarly, suppose we want to work with C sharp to code applications, etc. In that case, we will do so by using an Integrated Development Environment (such as Microsoft Visual Studio), but we are not to confuse a ‘console’ with a ‘console application.’ While a console is natively open in an IDE at all times, a ‘console application’ on the other hand, is simply an executable file that does not have a fancy GUI. The interface through which the user interacts with the application is like a simple command prompt. In such tasks, the most common action that you will likely perform during C sharp programming is implementing the classes you have defined in a certain console application. We can easily create a fresh console application by opening a ‘New Project’ within the IDE. The underlying code for the newly created console application is as follows: using System; namespace HelloWorld { /// <summary> /// Summary description for Class1. /// </summary> class Class1 { /// <summary>
/// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { // // TODO: Add code to start the application here // } } } Now let’s break this code down a bit. At the very start of this code block, we notice a statement being used, which is ‘using .’ The argument passed to this statement is ‘System .’ In this block of code, ‘System’ actually refers to a .’dll ’ assembly file available through the .’NET Framework ’ installed on our computer (using Windows, obviously). We do not need to go into the details as to ‘why’ a fresh console application is using the ‘System.dll ’ assembly file. A simple answer to this question of ‘why’ is that this file contains the necessary elements required for ‘Common Language Runtime.’ It wouldn't be wrong if we even said that the .’dll’ file is the console application itself. The ‘using ’ statement we use in C sharp is synonymous with the ‘include ’ statement in C++ and the ‘uses ’ statement in Delphi. In the next step, we specify the ‘name ’ of the console application through the ‘namespace ’ statement. The argument passed to this statement will be the name we assign the project, which in this case, would be the conventional name of the very first program created by
a user, i.e., ‘Hello World.’ However, in the argument, we do not add spaces in between a single namespace. The ‘slash’ symbols that you see in the middle of this block of code represent comments. Anything that is written after three/two slashes (\\\ or \\) is considered as additional commentary made by the programmer. Comments can be really helpful either when you need to go through the program's code later on its life cycle or if somebody else is exploring it. After the initial three comments, we will see the very first class is defined. Since this is a code generated when we create a default console application, the classes' names and constructs are standard. It is recommended that you name a class you create something that is self-explanatory, short, and easy to recall (although not every name can have all three of these elements). Up next, we have the core element of the entire application, the ‘Main() ’ member. If you have experience with C++, then you will be quite familiar with this member. Main is not a standard member. In fact, it has a special property that turns it into what we call a ‘static member .’ The property associated with a ‘static’ member is pretty useful. It allows us to use the method(s) associated with such a member without having an ‘enclosing class’ to exist. In addition, an argument known as ‘string[] args ’ tells us that a bunch of strings (in the form of an array) are passed to the Main static member. These strings are basically the ‘Command Line Arguments’ that you will generally pass during a coding session. Printing a Statement in a Console Application Now that we understand the underlying elements of a console application let’s build one to display a simple phrase, ‘Hello World!.’ To do this, we will simply be filling in the necessary arguments to the statements shown in the code of a console application. using System; namespace HelloWorld {
/// <summary> /// Summary description for Class1. /// </summary> class Class1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.ReadLine(); } } } To print out the phrase, we use two basic functions, namely, ‘Console.WriteLine() ’ and ‘Console.ReadLine() .’ We specify the phrase or sentence we want the console application to display and pass it as an argument to the ‘Console.WriteLine() ’ function. Once this is done, the ‘Console.ReadLine() ’ function then stands by until it receives the carriage return it expects before it continues with its job. The purpose of the ‘Console.WriteLine() ’ function is the same as the ‘cout>>’ statement in the C++ programming language.
When analyzing the usage of the methods to print out the phrase “Hello World!”, you might notice that these methods were used without including an instance of the corresponding ‘Console object.’ If this were a normal scenario, then you would be absolutely right, but the truth is that these methods are actually static members present in a class named ‘Console .’ So, if we want to call upon and use these methods, then we don’t need to create an instance of the corresponding class’s object. Performing a ‘Read’ on the Command Prompt We will now go over the approach through which we can effectively intercept the arguments specified to the console application. To do this, we simply pass a special argument to the ‘Console.WriteLine() ’ method. This argument is ‘args[0], ’ and you can see it being implemented in the following block of code: using System; namespace HelloWorld { /// <summary> /// Summary description for Class1. /// </summary> class Class1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args)
{ Console.WriteLine(args[0]); Console.ReadLine(); } } } When we execute this block of code, whenever we pass an argument to the command prompt, it is intercepted by the console application displayed on the console. Passing an argument to the command prompt can be done in two ways (there are other ways as well, but for the sake of simplicity, we will just stick with two). Execute an assembly through the command prompt and pass a corresponding argument. Using the Microsoft Visual Studio IDE to pass arguments to the command prompt. Let’s get into some details regarding the second method. Using the .’NET Visual Studio’ Integrated Development Environment is not that complex since you must have experience with other IDEs at this point. In order to use the IDE to pass an argument to the command line, we need to perform the following actions: 1. Open the Visual Studio IDE and look for the ‘Solution Explorer’ menu inside the ‘View’ tab. 2. Once you are inside the ‘Solution Explorer’ menu, you will find a list of all the projects that you have been working on or placed in the IDE’s browsing directory. Over here, you need to find the project you want to work on for this task and then just right-click it. This will open a drop-down menu, and from here, you select the ‘Properties’ option. 3. This will open a new window as shown below:
On the left-hand side, you will see a small file navigation interface. From here, double click ‘Configuration Properties,’ and inside, select ‘Debugging.’ 4. In the 3rd category named ‘Start options,’ the first section will be ‘Command Line Arguments.’ Over here, you need to specify an appropriate value. In this case, we pass an argument ‘Debugging C#.’ 5. Once we are done with passing a command-line argument, we can reboot the application we have opened in the IDE manually or by pressing the ‘F5 key’ as the shortcut key. Once the application runs using the IDE after a reboot, we will be able to see the argument passed to the command prompt. Using Fields and Properties ‘Fields’ and ‘Properties’ are elements that are interestingly related to each other, but before we can discuss them, let’s first understand the underlying concept of ‘consumers’ and ‘producers’ in programming. ‘Consumers ’ are those people that are the end-users of things like
classes. Similarly, ‘Producers ’ are those people that build these classes. An interesting thing to note here that both a consumer and a producer are programmers. Now with that clarified, let’s talk about ‘Fields .’ A ‘Field’ is simply a bunch of data that is contained within a class. Conventionally, the fields of a class are never public. Instead, they are set to ‘private’ by the producer, but there are times when consumers need access to the fields of a class they are using, but, since the fields are private, they are hindered. This is where ‘Properties ’ come in. Properties have the nature of duality. To elaborate, if a consumer is using this ‘Property Method,’ it will be indistinguishable as if the consumer were dealing with data. On the other hand, if the producer uses the same property method, it will function as if it were a method. You might ask why you would even need access to the data fields of a class in the first place. Well, the answer to that is very simple and straightforward, having access to the data of a class allows the programmer to have the freedom to make changes to the class’s methods and even perform some tweaks to the class's objects. Similarly, using ‘Properties ’ allows us to control how the data in the class is accessed. Defining a Field The nature of a field, i.e., the type of data it contains, can generally be anything (it just needs to conform to the purpose of the class in which it will be used). Since this data is important to the class, it is generally kept private through the use of access modifiers (i.e., setting its scope to ‘private’). In this way, only the programmer who created the field (the producer) will be able to make changes to it. If anyone other than the producer wants to access the fields in a class and make changes to it, they will have to do so through ‘Property Methods.’ In the following block of code, we are creating a field that stores string data. using System; namespace HelloWorld