Home > Article > Backend Development > Summary of conceptual systems in C#
1. What is .Net
.Net is an application development platform launched by Microsoft that can be used to build and run a new generation of Microsoft Windows and Web applications.
2. .Net core technology
.Net Framework: The core of the .Net platform core, providing a basic framework for the running of applications under the .Net platform.
.Net Enterprise Server: Microsoft provides part of the technical services to enterprises, including various development tool kits.
Building module service: COM+ component service and XML Web service technology provided by Microsoft use building module service to develop application modules, which can quickly assemble a fully functional software.
Visual Studio.Net: The main development tool for the .Net platform
3..Net Framework consists of different components to support the creation and running of applications based on the .NET platform.
4.. The bottom layer of the Net Framework framework is various application service components provided by the Windows operating system. These components include: message queue service, COM+ component service, Internet Information Service (IIS ), Windows Management Tools (WMI), etc.
5..Net Framework can be integrated with them to develop applications. The top level of .Net Framework is programming language. .Net Framework supports more than 20 computer programming languages. In the Visual Studio.Net development environment, you can directly use five languages: VB, C#, C++, J#, Jscript to develop any application.
6..Net Framework has two main components: Common Language Runtime (CLR) and .Net FrameworkClass Library, in addition to ADO.NET, ASP.NET, XML Web, etc.
7..Net Framework supports 3 types of user interfaces:
Command console, used to design applications with pure character interface
Windows Form, used to design applications with Windows interface
Web forms, applications used to design Web interfaces
8.ADO.NET is Microsoft's new generation of object-oriented data processing technology provided by the .Net Framework, using It can develop database applications easily and quickly.
ASP.Net is a new Web application development technology provided by the .Net Framework. Using ASP.NET to develop WEB applications is as easy as developing Windows applications.
Xml Web Service is a component that can be called directly in the Internet environment. The .Net Framework provides tools and classes for creating, testing, and deploying XML Web services.
9.Net Framework provides application developers with a platform-independent
development environment. Using .Net Framework to develop programs has the following advantages:
1. Web-based standards
.Net Framework fully supports existing Internet technologies and other web standards.
2. Use a unified application model Any language compatible with .NET can use the .Net Framework class library.
3. Easy for developers to use
When developers need to call a class of the .Net Framework class library, they only need to add the class
attribute namespace to Just quote in the solution. 4. Extensible classes
.Net Framework provides a universal type system. Developers can access classes in the class library through
inheritance, and can also extend classes in the class library, or even Build your own class library.
Advantages of C#: (1) C# is a precise, simple, type
safe, object-oriented language. (2) C# has the ability to generate persistent system-level components.
(3) C# uses the .Net Framework's universal type system to interoperate with other programming languages.
(4) C# supports MSMQ (Microsoft Message Queuing) service, COM+ component service, XML Web service and .Net Framework.
(5) C# allows customizing
data types and extended metadata. (6) C# enhances development efficiency while maintaining the flexibility required by developers.
Characteristics of C# programs: 4. The structure of methods in C# programs
A method in a C# program is
grouped into two parts: method header and method body. Method header: The header of the method is the first line of the method, including the return value type, method name, formal parameter name and formal parameter type description.
Method body: The method body is enclosed by a pair of curly brackets "{ }" and usually contains declaration statements and execution statements.
5. Statements of C# program
Each statement in the C# program must end with a semicolon. When writing, you can write several statements in one line, or you can write one statement in several lines. .
6. Input and output operations of C# programs
The C# language itself does not have input and output statements, so the C# console application must use the method of the Console class in the class library (ReadLine, WriteLine, etc.) to complete input, output and other operations, while C# Windows applications and Web applications must use the Control class (such as labels, text boxes, etc.) of the class library to achieve input and output.
7. Comments of C# program
You can use "//" or "/*...*/" to add comments. Appropriate addition of comments can greatly enhance the readability of the program.
Simple type represents a data type with a unique value, including the following 4
types: 1. Integer type 2. Floating point type3. Decimal type 4 . Boolean type
float type: the value range is ±1.5e?45 to ±3.4e38 and the accuracy is 7 digits
double type: the value range is ±5.0e?324 to ±1.7 The precision of e308 is 15 to 16 digits
3. Decimal type decimal In order to meet the needs of high-precision financial and financial calculation fields, C# provides decimal type data type
The value range is ±1.0?×?10e ?28 to ± 7.9? )
5. During the running of the program, the quantity whose value remains unchanged is called
constant
1, integer constant
Integer constants are divided into signed integer constants , unsigned integer constants and long integer constants
Signed integer constants are written directly, such as 5
Unsigned integer constants add the u or U sign when writing, such as 5U
long integer Add l or L mark when writing type constants, such as 5L
2. Floating-point constants
Floating-point constants are divided into single-precision floating-point constants and double-precision floating-point constants
Single-precision floating point Type constants are marked with f or F when written, such as 5F
Double-precision constants are marked with d or D, such as 5D
When written directly in decimal form, they are automatically interpreted as double-precision floating-point constants, such as 5.0 is a double-precision floating-point constant.
3. Decimal constants
The m or M mark must be added after the decimal constant, otherwise it will be interpreted as floating point data.
4. Character constants (Unicode characters):
Character constants are marked with two single quotes, such as the escape of '5', 'A', '中', '@'
C# Character constants start with a backslash '\' and are used to represent control and invisible characters. For example, '\b' means going back one character. For details, see Table 2-3 on P26 of the textbook
5. There are only two Boolean constants
, true means logically true, and false means logically false.
6.
String
ConstantString constant represents a character sequence composed of several Unicode characters, marked with double quotes, such as "5", "abc", "Chinese". Structural types must be marked with struct.
Structural members are allowed to include data members, method members, etc.
Data members represent the data items of the structure
Method members represent operations on data items.
1.
The concept of variables
The amount whose value can be changed during the running of the program is called a variable.
Variable name
: Each variable must have a name. Variable naming should follow the naming rules of identifiers. For example, it must start with a letter or underscore, and can only contain English letters, numbers, and underscores, and cannot contain spaces, etc. Variable value: Variable value is stored in memory; different types of variables occupy different numbers of memory units (bytes). In a program, the value of a variable is referenced by its name. 2. Definition of variables
The general form of variable definition is:
Data type Variable name 1, variable name 2,...;
For example: int a,b,c;
long x,y;
float p1,p2;
For example: C#算术运算符包括+、-、*、/、%、++、--共七种 声明和创建多维数组的一般形式: 上例中numbers[0]=1,……,numbers[4]=5 3. 数组的初始化 注意在先声明后初始化时,不能采用简写形式,例如: 是错误的float f1=1.25, f2=3.6;
值类型之间的数据可以相互转换,转换的方法有两种,一种是隐式转换,另一种是显式转换。
1. 隐式转换
如果参与运算的数据类型不相同,则先转换成同一类型,然后进行运算;
转换时按数据长度增加的方向进行,以保证精度不降低,例如int型和long型运算时,先把int数据转成long型后再进行运算;
所有的浮点运算都是以双精度进行的,即使仅含float单精度量运算的表达式,也要先转换成double型,再作运算;
byte型和short型数据参与运算时,必须先转换成int型;
Char型可以隐式转换为ushort、int、uint、long、ulong、float、double或decimal型,但不存在其他类型到char类型的隐式转换。
2. 显式转换
强制类型转换的一般形式为:
(类型说明符) (待转换的数据)
例如:(int)(x+y) //把x+y的值强制转换为int型
注意:上例不可写为(int)x+y,另外经过强制类型转换后x、y本身的变量类型并不会改变
3. C#还允许使用System.Convert类提供的类型转换方法来转换数据类型
常用的转换方法有ToBoolean 、ToByte、ToChar、ToInt32、ToSingle、ToString等
例如
byte x=40,y=5; //定义字节型变量x和y
byte z=Convert.ToByte(x+y); //将int型值转换为byte型并赋给byte型变量z
char c=Convert.ToChar(z+20); //将int型值转换为char型并赋给char型变量z
自增++/自减--运算符
当++或--运算符置于变量的左边时,称之为前置运算,表示先进行自增或自减运算再使用变量的值,而当++或--运算符置于变量的右边时,称之为后置运算,表示先使用变量的值再自增或自减运算
例如:设变量i=1、变量j=2,则表达式++i + j-- 的值为4
2. 复合赋值运算符
+=、-=、*=、/=、%=、&=、|=、^=、c1416f47236dd7b5b9b6ea098534dc8d>=
1. 什么是数组
数组是一种由若干个变量组成的集合,数组中包含的变量称为数组的元素,它们具有相同的类型。
数组元素可以是任何类型,包括数组类型。
数组元素的个数称为数组的长度,数组长度为0时称数组为空数组。
数组元素没有名称,只能通过索引来访问,索引从零开始。
具有 n 个元素的数组的索引是从 0 到 n-1。
C#支持一维数组和多维数组。
2. 数组的声明和创建
C#中的数组是一个对象,所以使用new运算符来创建
声明和创建一维数组的一般形式:
数组类型[ ] 数组名 = new 数组类型[数组长度];
如:int[ ] numbers=new int[5]; //创建具有5个元素的一维数组numbers
数组类型[逗号列表] 数组名 = new 数组类型[数组长度列表]
如:int[,,] numbers=new int[5,4,3]; //创建一个三维数组numbers
3. 数组的初始化
(1)在创建数组时初始化
创建一维数组时初始化的一般形式为:
数组类型[ ] 数组名 = new 数组类型[数组长度]{初始值列表};
如: int[ ] numbers=new int[ ]{1,2,3,4,5} ;//当省略数组长度时,则给出的数据个数即为数组长度
在创建并初始化数组时,还可采用简写形式:
数组类型[ ] 数组名 ={初始值列表}
如int[ ] numbers={1,2,3,4,5} ;
(2)在声明一维数组后初始化数组
在声明后初始化一维数组的一般形式为:
数组类型[ ] 数组名;
数组名 = new 数组类型[数组长度]{初始值列表};
如: int[ ] numbers;
numbers = new int[ ]{1,2,3,4,5} ;
int[ ] numbers;
numbers = {1,2,3,4,5} ;
4. 数组的使用:
每个数组元素相当于一个普通变量,使用数组元素的一般形式为:
数组名[索引]
C#的数组类型是从抽象基类型System.Array派生的引用类型, System.Array类提供的Length属性可以用来获得数组的个数。
另外System.Array提供了Clear、CopyTo、Find、Resize、Sort等方法,用于清除数组元素的值、复制数组、搜索数组、更改数组长度和对数组元素排序等。
5.System.String与 System.Text.StringBuilder
C#的string 是.NET Framework中System.String 的别名,可创建不可变的字符串。其提供的常用属性和方法有Length、Copy、IndexOf、LastIndexOf、Insert、Remove、Replace、Split、Substring、Trim等,分别用来获得字符串长度、复制字符串、从左查找字符、从右查找字符、插入字符、删除字符、替换字符、分割字符串、取子字符串、压缩字符串的空白等。
System.Text.StringBuilder类用来构造可变字符串,包含Length、Append、Insert、Remove、Replace、ToString等成员,分别用来获得字符串长度、追加字符、插入字符、删除字符、替换字符和将StringBuilder转换为string字符串。
对象(Object),是问题域中某些事物的一个抽象,反映事物在系统中需要保存的必要信息和发挥的作用,是包含一些特殊属性(数据)和服务(行为方法)的封装实体。
具体来说,对象应有唯一的名称、有一系列状态(表示为数据)、有表示对象行为的一系列行为(方法),如右图所示。
对象=数据+动作(方法/操作)
1. 事件(Event)
又称消息(Message)表示向对象发出的服务请求。
2. 方法(Method)
表示对象能完成的服务或执行的操作功能。
类(Class)是具有相同属性和服务的一组对象的集合
类为属于同类的所有对象提供统一的抽象描述。其中,相同的属性是指定义形式相同,不是指属性值相同。
对象是类的一个实例。
类与实例的关系是抽象与具体的关系,类是多个实例的综合抽象,实例是类的个体实物。
面向对象的最基本的特征是封装性、继承性和多态性:
1. 封装
封装就是指把对象的全部属性和全部服务结合在一起形成一个不可分割的独立单位。
封装是一种信息隐蔽技术,用户只能见到对象封装界面上的信息,对象内部对用户是隐蔽的。
封装的目的在于将对象的使用者与设计者分开,使用者不必了解对象行为的具体实现,只需要用设计者提供的消息接口来访问该对象。
例如,各种有标准视频接口的设备都可以连接电视机。
2.继承
特殊类的对象拥有其一般类的全部属性与服务,称作特殊类对一般类的继承,即在特殊类中不必重新定义已在一般类中定义过的属性和服务,这种特性在面向对象中称作对象的继承性。
继承在C#中称为派生,其中,一般类称为基类或父类,特殊类称为派生类或子类。
例如灵长类动物称为一般类,具有属性包括手和脚(其它动物没有),具有的服务是抓取东西(其它动物没有),人类作为特殊的灵长类高级动物,除了继承灵长类动物的所有属性和服务外,还具有特殊的服务(创造工具)。
继承机制的优势在于降低了软件开发的复杂性和费用,使软件系统易于扩充
3. 多态
多态性是指在基类中定义的属性或服务被派生类继承后,可以具有不同的数据类型或表现出不同的行为。
为了实现多态性,需要在派生类中更改从基类中自动继承来的数据类型或方法。
这种为了替换基类的部分内容而在派生类中重新进行定义的操作,在面向对象概念中称之为覆盖。
例如,假设机动车类是一个基类,它具有一个称为更换轮胎的方法,但是当从机动车派生火车类时,火车更话车轮的方法与一般的机动车不同,于是只能通过覆盖的方法在火车类中重新定义一个更换车轮的方法,以替换其基类的方法。
多态性的优势在于使软件开发更加方便,增加程序的可读性。
The constant member of a class is a symbolic constant, and the name and value must be specified.
Access modifiers include: public, private, internal, protected, protected internal.
When using access modifiers to define namespaces, structures, classes and their members
, please note:
(1) A member or type can only have one access modifier, when using protected internal combination except.
(2) Access modifiers are not allowed on the namespace, and there are no access restrictions on the namespace.
(3) If the access modifier is not specified, the default accessibility is used, and the class members default to private.
(4) The accessibility of top-level types (types not nested in other types) can only be internal or public, and the default accessibility is internal.
Detailed description of defining methods
(1) Access modifiers control the access level of methods. Modifiers that can be used for methods include: public, protected, private, internal, etc.
(2) The return value type of a method can be any legal data type, including value types and reference types. When there is no return value, the return value type is represented by the void keyword.
(3) The method name must comply with the C# naming convention, which is the same as the variable name naming rule.
(4) The parameter list is the input data that the method can accept. When a method does not require parameters, the parameter list can be omitted, but the parentheses cannot be omitted. When there is more than one parameter, commas need to be used as separation, and each parameter must declare the data type, even if the data types of these parameters are the same.
(5) The content in curly braces {} is the body of the method, which consists of several statements. Each statement must end with a semicolon. If you need to return the operation result when the method ends, use the return statement to return. At this time, please note that the type of the value returned by the return statement must match the method return value type. If the method is marked as void and has no return value, the return statement can be omitted.
1. Value type parameters
When calling a direction method to pass a value type parameter, the caller will assign the value of the actual parameter variable to the corresponding formal parameter variable, that is, the actual parameter variable and the formal parameter variable are Two different variables.
When the value of the actual parameter variable is passed to the formal parameter variable, it is a one-way value transfer.
Reference type parameters
Different from value parameters, when the calling direction method passes a reference type parameter, the caller will assign the reference of the actual parameter variable to the corresponding formal parameter variable. The reference of the actual parameter variable represents the memory address of the data value, so the formal parameter variable and the actual parameter variable will point to the same reference.
If the data value referenced by the formal parameter variable is changed inside the method, the data value referenced by the actual parameter variable is also modified.
Since the return statement can only return one data at a time, if you need to return multiple data, you can use this feature of reference parameters to achieve it.
C# declares reference parameters through the ref keyword, whether it is a formal parameter or an actual parameter. As long as you want to transfer a reference to the data, you must add the ref keyword.
Output parameters
The return statement in the method can only return one operation result. Although reference parameters can also be used to return the calculation result, the actual parameters are required to be initialized first.
The output parameter does not need to initialize the actual parameters. It is specially used to return the data in the method to the actual parameters through the formal parameters, but the value of the actual parameters will not be passed to the formal parameters. Multiple output parameters are allowed in a method.
C# uses the out keyword to declare output parameters. Whether it is a formal parameter or an actual parameter, as long as it is an output parameter, the out keyword must be added.
Array type parameters
There are two ways to use arrays as parameters:
One is to not add the params modifier before the formal parameter group
The other is to add params before the formal parameter group modifier.
The difference between the two forms
When the params modifier is not added, the corresponding actual parameter must be an array name.
When adding the params modifier, the corresponding actual parameter can be an array name or a list of array element values.
It is worth noting that no matter which form is used, the formal parameter group cannot define the array length.
Method overloadingOverloading
Method overloading refers to declaring two or more methods with the same name in the same type. Method overloading can be useful when you need to perform the same operation with a different parameter list.
2. Characteristics of the destructor:
(1) The destructor cannot be defined in the structure, and the destructor can only be used for the class;
(2) A class can only have one destructor;
(3) The destructor cannot be inherited or overloaded;
(4) The destructor has neither modifiers nor parameters;
(5) In When the destructor is called, the .Net Framework's CLR automatically adds a call to the base class Object.Finalize method to clean up the scene, so a call to the Object.Finalize method cannot be included in the destructor.
Note that by default, the compiler automatically generates an empty destructor, so C# does not allow the definition of an empty destructor
1. Definition of static class:
A static class is declared using the static keyword , indicating that it only contains static members.
You cannot use the new keyword to create instances of static classes.
In practical applications, when the members of a class are not associated with a specific object, it can be created as a static class.
2. The main functions of static classes:
(1) Static classes only contain static members;
(2) Static classes cannot be instantiated;
(3) Static classes are sealed ;
(4) Static classes cannot contain instance constructors .
3. Advantages of static classes:
(1) The compiler can automatically perform checks to ensure that instance members are not added;
(2) Static classes can make program implementation simpler and faster , because you don't have to create an object to call its methods.
Note: Because static classes are sealed, they cannot be inherited. In addition, static classes cannot contain instance constructors, but they can still declare static constructors to assign initial values or set some static state.
(1) Characteristics of derived classes
can have its own members.
You can implicitly inherit all members from the base class, including methods, fields, properties and events, except private members, constructors and destructors.
Derived classes can only inherit from one class
Sealed class
Using a sealed class can prevent the code of a class from being inherited by other classes
Benefits of using a sealed class:
Can improve the performance of the application Reliability and performance (in the .NET Framework common language runtime CLR, method calls to sealed classes are optimized when loading sealed classes).
Software companies can also protect their intellectual property rights by using sealed classes to prevent others from sharing code.
In C#, add the keyword sealed to declare a sealed class.
4. In order to use derived classes to change the data and behavior of base classes, C# provides two options: 1. Use new derived class members to replace base members 2. Override virtual base members
Pay attention to the following points when using virtual and override:
(1) Fields cannot be virtual, only methods, properties, events and Only indexers can be virtual;
(2) After using the virtual modifier, the static, abstract or override modifiers are not allowed to be used;
(3) Even if a derived class object is forced to be a base class object, What is referenced is still a member of the derived class;
(4) The derived class can stop virtual inheritance by sealing. At this time, the members of the derived class are declared using sealed override.
Characteristics of abstract classes:
Abstract classes are used as base classes and cannot be instantiated directly, and can only be identified using the abstract keyword. The purpose of an abstract class is to provide a common definition of a base class that can be shared by multiple derived classes.
Abstract classes can contain abstract members, such as abstract properties and abstract methods, as well as non-abstract members, and even virtual methods.
Characteristics of abstract attributes
After the abstract keyword is added to the attribute members of the class, they become abstract attributes.
The abstract property declaration does not provide the implementation of the property accessor. It only declares the properties supported by the class and leaves the implementation of the accessor to the derived class.
Abstract properties can also be read-only, write-only, or read-write properties.
When a derived class inherits an abstract property from an abstract class, the derived class must override the abstract property.
Abstract attributes use the abstract keyword to identify
Characteristics of abstract methods:
After adding the abstract keyword to the method members of the class, they become abstract methods.
Abstract method declaration does not provide method implementation, it must be an empty method, leaving method implementation to derived classes.
When a derived class inherits an abstract method from an abstract class, the derived class must override the abstract method.
Since the abstract method is not implemented, the abstract method does not contain a regular method body and ends with a semicolon.
1. Delegate is a type of reference method. It is the same as class, interface and array and belongs to reference type.
In a C# program, you can declare a delegate type, define variables of the delegate type, assign methods to delegate variables, and indirectly call one or more methods through delegates.
Once a method is assigned to a delegate, the delegate will behave exactly the same as the method.
C# allows any method with the same signature (same return value and parameters) to be assigned to a delegate variable.
The essence of delegation is the reference of the representative method (i.e., the memory address). It is an ideal choice for defining callback methods and is also the main way for C# to implement the event driven programming model.
Delegation has the following characteristics:
(1) Delegation is similar to C++ Function pointer, which is completely object-oriented and a safe data type.
(2) Delegate allows methods to be passed as parameters.
(3) Delegate can be used to define callback methods.
(4) Delegates can be linked together. For example, multiple methods can be called on an event.
(5) The delegate signature does not need to match the method exactly.
Collections are classes that store arbitrary objects in a highly structured way. Compared with arrays that cannot be dynamically resized, collections can not only be resized at will, but also provide more advanced methods for storing or retrieving objects stored in them. .
Collections can group together a group of similar typed objects.
When choosing a collection class, you should generally consider the following issues:
(1) Whether you need a sequence list, you can use the Queue queue class when you need first-in-first-out behavior, and you can use the Stack class when you need last-in-first-out behavior. .
(2) Whether you need to randomly access the elements in the collection, you cannot choose the Queue queue class, Stack stack class, or LinkedList doubly linked list class.
(3) Do you need to access each element through index? Only the ArrayList dynamic array class, StringCollection string collection class, etc. access the collection elements one by one starting from the element with index zero. Hashtable Hash table and Dictionary dictionary classes provide access to elements through the key of the element (that is, the element name). The NameValueCollection class and the SortedList generic class provide access to elements through their element's zero-based index, or through its element's key.
(4) Whether it contains a value, a key and a set of values, or a set of one key and multiple values. Among them, the collection of "one value" is a collection derived based on the IList list interface, the collection of "one key and one value" is a collection based on the IDictionary dictionary interface, and the collection of "one key and multiple values" is NameValueCollection kind.
(5) Whether the elements need to be sorted differently from the input elements. The Hashtable hash table class sorts elements according to their hash codes, the SortedList ordered list class and the SortedDictionary ordered dictionary implement sorting of elements by key according to the IComparer comparable interface, and the ArrayList dynamic array class provides the Sort sorting method.
(6) Whether you need fast search and retrieval of information, for small collections (10 elements or less), ListDictionary is faster than Hashtable, and the SortedDictionary generic class provides faster lookup than the Dictionary generic class.
(7) Do you need to accept only a collection of strings, such as using StringCollection and StringDictionary, etc.
Dynamic array class ArrayList does not limit the number and data type of elements.
(1) The difference between ArrayList and Array
The size of Array is fixed, while the size of ArrayList can be automatically expanded as needed;
In Array, you can only get or set the value of one element at a time, while in Array ArrayList allows adding, inserting or removing a range of elements;
The lower limit of Array can be customized, while the lower limit of ArrayList is always zero;
Array can have multiple dimensions, while ArrayList is always only one-dimensional ;
Array is located in the System namespace, and ArrayList is located in the System.Collections namespace.
(2) Create a dynamic array:
ArrayList list object name = new ArrayList(?);
Characteristics of queue
A first-in-first-out data structure. When an object is inserted or deleted, the object Insert from one end of the queue and remove from the other end
Create queue object
Queue queue name = new Queue([queue length][, growth factor]);
Explanation, the queue length defaults to 32, growth The factor defaults to 2.0 (that is, whenever the queue capacity is insufficient, the queue length is adjusted to 2 times the original value)
Note that since adjusting the queue size requires a certain performance cost, it is recommended to specify the queue length when constructing the queue.
Common queue operation methods include Enqueue to add data to the end of the queue, Dequeue to remove data from the head of the queue, Peek to return data from the head of the queue, Clear to empty the queue, and Contains to check whether a certain data is included. Among them, Enqueue and Dequeue can only add or delete one piece of data at a time.
Features of the stack:
A first-in, last-out data structure. When inserting or deleting an object, this data structure can only be inserted or deleted at the top of the stack.
Create stack object:
Stack stack name = new Stack(?);
Common stack methods include Push to add data on the top of the stack, Pop to remove the top data of the stack, Peek to return the top data of the stack, and Clear to clear the stack. and Contain to check whether it contains certain data, etc. Among them, Push and Pop can only add or delete one piece of data at a time.
Hash table, also known as hash table, represents a collection of key/value pairs.
Features of the hash table: When saving a collection element, the hash code must be automatically calculated based on the key to determine the storage location of the element, and then the value of the element is placed in the bucket pointed to by the corresponding location. When searching, search in a specific bucket again by the hash code corresponding to the key. This greatly reduces the number of comparisons required to find an element.
Create a hash table object
Hashtable Hash table name = new Hashtable([hash table length][, growth factor]);
Explanation, the default length is 0, and the default growth factor is 1.0
Common operation methods of hash tables include Add to add data, Remove to remove data, Clear to clear the hash table, and Contains to check whether certain data is included. Among them, the Add method requires two parameters, one is the key and the other is the value; the Remove method only requires one key parameter.
There are two differences between the interface indexer and the class indexer:
First, the interface indexer does not use modifiers;
Second, the interface indexer only Contains accessor get or set, no implementation statement.
When creating a custom generic class, you need to pay special attention to the following matters:
(1) Which types should be generalized as type parameters
The general rule is: the more types that can be parameterized, the more code will The more flexible you become, the better your reusability, but too much generalization can make it difficult for other developers to read or understand the code.
(2) If constraints exist, what constraints should be applied to the type parameters
The general rule is: apply as many constraints as possible, but still be able to handle the types that need to be processed. For example, if you know that a generic class will only be used for reference types, apply class constraints. This prevents generic classes from being accidentally used for value types.
(3) Whether to decompose generic behavior into base classes and subclasses
Since generic classes can be used as base classes, their precautions are the same as non-generic classes.
(4) Whether to implement one or more generic interfaces.
Event processingComponents of the system
(1) Event source: refers to the object that can trigger the event, sometimes also called the sender of the event or the publisher of the event;
(2 ) Listener: refers to an object that can receive event messages. Windows provides basic event listening services;
(3) Event handler: handles events when events occur, also called event functions or event methods , the object containing the event handler is called the receiver of the event, also known as the subscriber of the event.
Events in C# have the following characteristics:
(1) Events are a way for classes to notify objects that they need to perform a certain operation;
(2) Although events can occur at other times (such as signal state changes) Very useful, but usually used in graphical user interfaces;
(3) Events are usually declared using delegate event handlers;
(4) Events can call anonymous methods instead of delegates.
1. The Basic concept of events
The object that triggers the event is called the publisher, and the object that provides the event handler is called the subscriber. In the .NET Framework, event-driven programs use delegates to bind events and event functions. In C#, an event is actually a delegate type variable.
C# allows you to use the built-in EventHandler delegate type to declare a standard event, and also allows you to customize the delegate first and then declare the custom event.
In the .NET Framework, the built-in EventHandler delegate has two parameters, their data types are Object and EventArgs types, and there is no return value.
The Object parameter name is usually sender, which represents the event publisher itself; the EventArgs parameter is usually e, which passes a new instance of the System.EventArgs class to the event function. In actual programming, sometimes it is necessary to derive a custom event parameter class from the EventArgs class so that the publisher can send specific data to the receiver's event function.
Event declaration
(1) Use the built-in EventHandler delegate to declare the event form (standard event)
Format: public event EventHandler event name;
Among them, the event name usually uses on as the prefix.
For example, public event EventHandler onClick;
(2) Use a custom delegate type to declare events
Format: public delegate return value type delegate type name ([parameter]);
Parameters of the function match. Be sure to grasp the following points when subscribing to events:
(1) First, the receiving class must have a method with the same signature (same return value type and parameters) as the event itself, and then the method (called event processing program) can take appropriate action in response to the event.
(2) Each event can have multiple handlers, and multiple handlers are called in sequence. If a handler throws an exception, handlers that have not been called yet have no chance to receive the event. For this reason, it is recommended that event handlers handle events quickly and avoid throwing exceptions.
(3) To subscribe to an event, the receiver must create a delegate of the same type as the event, use the event handler as the delegate target, and also use the
additive assignment operator (+=) Add the delegate to the source object's event. (4) To unsubscribe from an event, the receiver can use the subtraction assignment operator (?=) to remove the delegate of the event handler from the source object's event.
1. Windows Forms
Windows Forms are the starting point for building window-based applications using C#. However, from the perspective of the form itself, it is just a movable interface. Although users can draw objects and text directly on the form, the real role of the form is to act as a container for Windows controls.
The essence of the control is the member object of the form, which is used to display information and receive user input information.
2. Windows Forms namespace
The base class of Windows Forms is Form, in the System.Windows.Forms namespace Definition.
Most controls in .NET are derived from the System.Windows.Forms.Control class, which defines the basic functionality of the control.
Form controls in .NET Framework
Data display DataGridView
Data binding and positioning BindingSource, BindingNavigator
Text Edit TextBox, RichTextBox, MaskedTextBox
Information display Lable, StatusStrip, ProgressBar
Web page display WebBrowser
List and selectionCheckBox, CheckedListBox, ComboBox, RadioButton, ListBox, ListView, NumericUpDown, TreeView, DomainUpDown, TrackBar,
Graphic Display PictureBox, ImageList
Date Settings DateTimePicker,MonthCalendar
Dialog ColorD ialog, FontDialog, OpenFileDialog, PrintDialog, PrintPreviewDialog, FolderBrowerDialog, SaveFileDialog
Command Button, LinkLabel, NotifyIcon, ToolStrip
Menu MenuStrip, ContextMenuStrip
User Help HelpProvider, ToolTrip
Replace other controls Grouping Panel, GroupBox, TabControl, SplitContainer, TableLayoutPanel, FlowLayoutPane
Properties of the control
Property name Description
Anchor Get or set the control Binds to the edge of the container and determines how the control resizes with its parent
BackColor The background color of the control
Bottom Under the control The distance between the edge and the upper edge of the client area of its container (unit: pixels)
Dock Gets or sets the control border docked to its parent control and determines how the control resizes with its parent
Enabled Whether the control can respond to user interaction
ForeColor The foreground color of the control
Height The height of the control
Left The distance between the left edge of the control and the left edge of the client area of its container (unit: pixels)
Location The upper left corner of the control relative to The coordinates of the upper left corner of its container.
Name The name of the control. This name can be used to reference the control in code.
Parent The parent container of the control
Right The distance between the right edge of the control and the left edge of the client area of its container (unit: pixels)
Size The height and width of the control
TabIndex The tab key sequence of the control
TabStop Indicates whether the user can Use the Tab key to place focus on the control.
Text Text associated with this control
Top The distance between the upper edge of the control and the upper edge of the client area of its container (unit: pixels)
Visible Indicates whether to display the control
Width The width of the control
ButtonControl
Button (button) control is located in the .NET Framework System.Windows.Forms namespace, which is derived from the base class ButtonBase. The base class ButtonBase is used to implement the basic operations required by button controls.
Button control is a commonly used control. When users are required to make choices such as "OK" or "Cancel", Button control is usually used. The Button control supports mouse click and double-click operations, and can also be operated with the 148abe006775c52e28d07bbe171fd752 key.
When designing, you usually add a control on the form, then double-click it and write code for the Click event. When the program is executed, clicking the button will execute the code in the Click event.
Name attribute: used to set the name of the object for reference in code.
The system automatically names the Button control button1, button2...
It is best to set a meaningful name for the Name property.
The Name property of various control objects can only be changed through the "Properties" window. This property is valid at design time and is read-only at runtime.
Text attribute: The title text displayed on the button in text form.
In addition to clicking the button, you can also define "Alt+shortcut key" for the button, see Figure 7-2 on P155.
Define method, add an "&" character in front of the shortcut key letter.
For example: button1.Text = "OK(&Y)"; //The display title is "OK(Y)"
Visible attribute: determines whether the button is visible
The attribute value is true to be visible, false to hide.
When a control is invisible, it cannot respond to the user's mouse and keyboard operations.
Visible properties take effect at runtime.
Enabled attribute: determines whether the button is valid
When the attribute value is false, the button text is displayed in gray and does not respond to user operations.
FlatStyle attribute: determines the style of the button, the value is FlatStyle enumeration type
FlatStyle enumeration type has 4 enumeration values, namely Flat (flat display), Popup (flat display, but mouse When moved, the appearance is three-dimensional), Standard (three-dimensional display), and System (the appearance is determined by the operating system). The effect is shown in Figure 7-3 on P156.
The FlatStyle property of the Button control defaults to Standard.
Image property: Specify an image to be displayed on the button
ImageAlign property: Set the alignment of the image on the button
Label control
Function: Mainly used to display text on the form
Control name:
Label: standard Windows label;
LinkLabel: similar to Label, but displayed in the hyperlink way. The effect is shown in Figure 7-4.
Normally, there is no need to add event processing code to the Label control, but events can also be supported when needed.
Common properties of label controls
Property name Description
BorderStyle The border style of the control, the default is borderless
FlatStyle Set the flat style appearance. If set to PopUp, it means a flat style. When the mouse points to it, the control will appear in a pop-up style.
Image The image displayed on the Label
ImageAlign The alignment of the image displayed in the control
LinkArea The text displayed as a link Range (only for LinkLabel)
LinkColor The color used when displaying ordinary links (only for LinkLabel)
Links Get the collection of links contained in the LinkLabel ( Only for LinkLabel)
LinkVisited Whether the link appears as a visited link (only for LinkLabel)
TextAlign? Alignment of the text in the label
VisitedLinkColor The color used when displaying previously visited links (only for LinkLabel)
Text box control
.NET FrameWork has two built-in text box controls: TextBox control and RichTextBox control. They all derive from TextBoxBase, which derives from the Control class.
TextBoxBase provides basic functions for processing text in text boxes, such as text selection, cut and paste, and related events.
TextBox is mainly used to allow users to input text. It can also specify the type of characters entered by the user, such as allowing only numerical values. By default, a text box can enter up to 2048 characters. If you set the Multiline property to true, you can enter up to 32k text. User text is stored in the Text property, and the text entered by the user can be obtained by referencing the Text property in the program. RichTextBox is mostly used to display and enter formatted text (TextBox is often used to enter shorter text characters). RichTextBox can display fonts, colors and links, load text from files and load embedded images, and find specified characters. RichTextBox is also used Called an enhanced text box.
TextBox control
Property name Description
CausesValidation? Whether to verify the validity of user input
CharacterCasing Whether to modify the case format of characters when typing them
MaxLength? Set the maximum number of characters that can be entered, if =0, there is no limit
Multiline Is it possible? Display multi-line text
PasswordChar Set password display characters
ReadOnly? Whether the text is read-only
ScrollBars Get or set which scroll bars Should appear in a multi-line TextBox control
SelectedText? Represents the currently selected text
SelectionLength? The number of characters currently selected
SelectionStart? The starting point of the currently selected text
Text Current text
WordWrap? Whether to wrap automatically
Event name Description
Enter? Occurs when entering the controlThese 4 events are triggered in the order listed. They are called "focus events" when the focus of the control changes. is triggered, but Validating and Validated are only triggered when the control receives focus and its CausesValidation is set to true
Leave? Occurs when the input focus leaves the control
Validating? Occurs while the control is validating
Validated? Occurs when the control completes validation
KeyDown These three events are collectively called "key events" and are used to monitor and change the content input into the control. KeyDown and KeyUp? receive the key code corresponding to the pressed key, which can be used to determine whether a special key is pressed, such as Shift , Ctrl or F1. KeyPress receives the characters corresponding to the key
KeyPress
KeyUp?
TextChanged? As long as the text in the text box changes, this event will be triggered
RichTextBox control
Property name Description
CanRedo? Indicates whether there are operations that can be reapplied among the operations that occurred within the RichTextBox
CanUndo? Indicates that the user can re-apply the text Can the previous operation be undone in the box control?
DetectUrls When a URL is typed in the control, whether RichTextBox automatically sets the format of the URL
Rtf Related to the Text property Similar, but can include text in RTF format
SelectedRtf Gets or sets the formatted text in RTF format currently selected in the control
SelectedText Gets or sets the selection in the RichTextBox Define the text
SelectionAlignment The alignment of the selected content or insertion point, which can be Cente, Left, or Right
SelectionBullet? Indicates whether the bullet style is applied to the current Selection or insertion point
BulletIndent? Specifies the indent pixel value of the bullet
SelectionColor Gets or sets the text color of the currently selected text or insertion point
SelectionFont Gets or sets the font of the currently selected text or insertion point
SelectionLength? Gets or sets the number of characters selected in the control
ShowSelectionMargin If this property is set to true, a margin will appear on the left side of the RichTextBox to facilitate text selection
UndoActionName Get the call The name of the undoable operation in the control after the Undo method
SelectionProtected Set this property setting to true, you can specify not to modify certain parts of the text
RadioButton control
Property name illustrate
Appearance Gets or sets a value that determines the appearance of the RadioButton.
Optional values: Normal and Button. Each type can display text or images, or both.
Appearance after selecting Normal: . Appearance after selecting Button:
AutoCheck If this property is true, when the user clicks the radio button, a check mark will be displayed. If this property is false, you must manually check the radio button
CheckAlign in the code of the Click event handler to change the alignment form of the radio button's checkbox, value Can be one of the valid values of the ContentAlignment enumeration. The default value is MiddleLeft, which means that the content is aligned in the middle in the vertical direction and left aligned in the horizontal direction
Checked Gets or sets a value that indicates whether the control has been selected. If the control is selected, it is true, otherwise it is false
GroupBox control
GroupBox (group box) control is used to provide identifiable grouping for other controls. Typically, you use group boxes to subdivide your form by function.
When a single GroupBox control is moved, all controls it contains will also move together.
When creating a GroupBox control and its internal controls on a form, you must first create the GroupBox control, and then create various controls within it.
Panel control
Panel (Panel) control is similar to the GroupBox control. The difference between the two is that only the GroupBox control can display a title, and only the Panel control can have scroll bars.
To display scroll bars, set the AutoScroll property to true.
You can customize the appearance of the panel by setting the BackColor, BackgroundImage and BorderStyle properties.
TabControl control
Property name Description
Alignment Control the display position of the tab in the control, the default is the top of the control
Appearance Control how tabs are displayed. Tabs can be displayed as general buttons or with flat styles
HotTrack If true, when the mouse pointer moves over the tab on the control, Its appearance will change
Multiline If true, the tab can be displayed in multiple rows
RowCount Returns the currently displayed tab Number of rows
SelectedItem Gets or sets the index of the currently selected tab page
SelectedTab Gets or sets the currently selected tab page. This property is in TabPages Use
TabCount on the instance to get the number of tabs in the tab strip.
TabPages Get the collection of tab pages in the tab control. Use this collection to add and delete TabPages objects
Common properties of panes in the StatusStrip control
Property name Description
AutoSize Whether to automatically adjust the size of the item based on the item's image and text
Alignment Set the upper pane of the StatusStrip control Alignment, the options include: Center, Left and Right
BorderStyle Set the style of the pane border, the options are as follows:
None: Do not display the border; Raised: The pane is convex in three dimensions Sunken: The pane is displayed in a three-dimensional concave manner
Image Set the icon displayed by the pane
MinimumSize Set the size of the pane in the status bar Minimum width
Spring Whether the specified item fills the remaining space
Text Set the displayed text of the pane
Width Set the pane The width depends on the setting of the AutoSize property. When the size of the form changes, the property value may change accordingly.
The Show method will return a DialogResult enumeration value to indicate the return value of the dialog box
Member Description
Abort The return value of the dialog is Abort (usually sent from the button labeled "Abort")?
Cancel Dialog The return value of the box is Cancel (usually sent from the button labeled "Cancel")?
Ignore The return value of the dialog box is Ignore (usually sent from the button labeled "Ignore")?
No The return value of the dialog box is No (usually sent from the button labeled "No")?
None Nothing was returned from the dialog box. This indicates that the modal dialog box continues to run?
OK The return value of the dialog box is OK (usually sent from the button labeled "OK")?
Retry Dialog The return value of the box is Retry (usually sent from the button labeled "Retry")?
Yes The return value of the dialog box is Yes (usually sent from the button labeled "Yes")?
Drive
.NET Framework provides the DriveInfo class and DriverType enumeration type to facilitate the direct use of drives in programs. The DriveInfo class and DriverType enumeration are located in the System.IO namespace.
DriveInfo class
Function: Determine information about the drive, including drive letter, drive type, available space on the drive, etc.
Common members:
Field: DriveFormat (File systemFormat, such as NTFS or FAT32), DriveType (drive type), Name (drive name), TotalSize (total space), TotalFreeSpace (available space)
Method: GetDrives (get the list of available drives)
perType enumeration type
The enumeration values include CDRom (optical drive), Fixed (hard disk), Network (network drive), Removable (floppy disk or U disk), etc.
Directory
Provided by .NET FrameworkDirectory class and DirectoryInfo class to facilitate direct manipulation of the directory in the program. The Directory class and DirectoryInfo class are located in the System.IO namespace and can be used to create, copy, move or delete directories.
Directory Class
Features: Static class, its method members can be called directly, but each method member called must perform a security check to determine the user's operation permissions.
Common method members: CreateDirectory (create a new directory), Delete (delete the directory), Exists (determine whether the directory exists), Move (move the directory), GetFiles (get the file list of the directory), GetDirectories (Get a list of subdirectories), etc.
DirectoryInfo class
Features: Non-static class (must be instantiated), an instance needs to be created before its method members can be called, and security checks are performed when creating an instance.
Common field members; Name (extract directory name), Exists (whether it exists), Parent (parent directory), Root (root directory)
Common method members: Create (create directory), CreateSubDirectory (create subdirectory) , Delete (delete directory), MoveTO (move directory), GetFiles, GetDirectories, etc.
Code example: P197
File
NET Framework provides the File class and FileInfo class to facilitate the program directly manipulate files. The File class and FileInfo class are located in the System.IO namespace and can be used to create, copy, delete, move, open files and other operations.
File Class
Features: Static class, its method members can be called directly.
Common method members: Open (open a file), Create (create a new file), Copy (copy a file), Delete (delete a file), Exists (determine whether a file exists), Move (move a file), Replace (replace a file) ), AppendAllText (create a new file and add text), ReadAllText (open and read text content), etc.
FileInfo class
Features: Non-static class, you need to create an instance first.
Common field members: Name (extracted file name), Directory (directory to which it belongs), Exists (whether it exists), Extension (file extension), Length (file length), IsReadOnly (whether it is a read-only file)
Common method members: Open, Create, CopyTo (copy to new file), Delete, MoveTo (move file), Replace, EnCrypt (encrypt file), Decrypt (decrypt file), etc.
Code example: P198
Path
The location of the file is called the path. The path consists of the drive letter, directory name, file name, file extension, and delimiter.
How to express the path
Absolute path: Start writing from the root directory of the drive, such as C:\Windows\System32\notepad.exe
Relative path: Start writing from the current directory location, such as System32\nodepad. exe (assuming the current directory is C:\Windows)
C# treats the "\" character as an escape character, so when the path is expressed as a string, use two backslashes, for example:
" C:\\Windows\\System32\\notepad.exe"
C# allows adding the "@" sign before the string to prompt the compiler not to treat the "\" character as an escape character, but as an ordinary character , For example:
@"C:\Windows\System32\notepad.exe"
NET Framework provides the Path class to help manage file and directory paths in programs. The Path class is located in the System.IO namespace and is a static class.
Path class function: static class, used to operate each field of the path, such as drive letter, directory name, file name, file extension and delimiter, etc.
Path common field members: PathSeparator (path separator), DirectorySeparatorChar (directory separator), VolumeSeparatorChar (volume separator)
Path common method members: GetDirecotryName (get directory name), GetFileName (get file name), GetExtension (get file extension), GetFullPath (get the full path), GetTempPath (get the temporary file path of the operating system), etc.
The flow includes the following basic operations.
Read (read): means transferring data from a stream to a certain data structure, such as outputting to a byte array;
Write (write): means transferring data from a certain data structure to a stream , for example, transmitting data in a byte array to a stream;
Positioning (seek): Indicates querying or relocating the current position in the stream.
Classes that operate streams
(1) Stream class
The Stream class is the abstract base class of all streams.
Main properties of the Stream class: CanRead (whether reading is indicated), CanSeek (whether search is supported), CanTimeout (whether timeout is possible), CanWrite (whether writing is supported), Length (length of the stream), Position (Get or set the position in the current stream), ReadTimeout (get or set the timeout for the read operation), WriteTimeout (get or set the timeout for the write operation)
The main method of the Stream class: BeginRead (start Asynchronous read operation), BeginWrite (start asynchronous write operation), Close (close the current stream), EndRead (end asynchronous read operation), EndWrite (end asynchronous write operation), Flush (clear all buffers of the stream) And write the buffered data to the basic device), Read (read a byte sequence), ReadByte (read a byte), Seek (set the search position), Write (write a byte sequence), WriteByte (write a word Section)
(2) StreamReader and StreamWriter classes
Generally used to operate text files
The stream reader StreamReader class is used to read characters from a byte stream in a specific encoding.
The StreamWriter class is used to write characters to the stream in a specific encoding.
(3) FileStream, MemoryStream and BufferStream classes
File stream FileStream class: read, write, open, and close files in the form of streams.
MemoryStream MemoryStream class: Indicates creating a stream in memory to temporarily save data. With it, there is no need to create temporary files on the hard disk.
CacheStream BufferStream class: First add the stream to the buffer, and then perform read/write operations. Using the buffer can reduce the number of calls to the operating system when accessing data.
Note that the FileStream class also has a buffering function. When creating an instance of the FileStream class, you only need to specify the size of the buffer.
Reading and writing text files
A text file is a file composed of pure text data, which only saves the encoding of characters.
Character encoding supported by NET Framework
Can be ASCIIEncoding, UTF7Encoding, UTF8Encoding, UnicodeEncoding or UTF32Encoding
Reading and writing text files in .NET Framework mainly uses:
File reader TextReader class and text writing TextWriter class
Their derived classes stream reader StreamReader class and stream writer StreamWriter class
or StringReader and StringWriter classes
TextReader class and its derived classes common methods:
Close(Close reader and release system resources), Read (read the next character, if it does not exist, return -1), ReadBlock (read a block of characters), ReadLine (read a line of characters), ReadToEnd (read from the current position to all characters until the end)
Commonly used methods of the TextWriter class and its derived classes:
Close (close the writer and release system resources), Flush (clear all buffers of the current writer, so that all buffered data is written to the base Device), Write (write text stream), WriteLine (write a line of data)
ASP.NETIntroduction
ASP.NET is a dynamic web design technology that is better than any other This dynamic web design technique is easier to use. It is a scalable web application development technology that is particularly good at user interaction and data processing.
ASP.NET is not a programming language. It is a programming framework based on the .NET Framework. It is used to create Web applications.
The syntax of ASP.NET is compatible with ASP, but ASP applications cannot run directly in the ASP.NET environment and need to be modified appropriately.
The biggest difference between ASP.NET and ASP is that the former is a compiled dynamic web page technology, while the latter is an interpreted dynamic web page technology.
The more popular versions of ASP.NET are version 1.1, version 2.0 and version 3.0. ASP.NET released with Visual Studio.NET 2003 is version 1.1, and ASP.NET released with Visual Studio.NET 2005 is version 2.0. ASP.NET, released in 2007 with Visual Studio.NET 2008, is version 3.0.
Advantages of ASP.NET
Manageability is good
Security is high
Easy to deploy
Performance is greatly enhanced compared to ASP and JSP
Flexible output caching technology
Using Unicode encoding, internationalization is achieved
Supports mobile devices
Good scalability and usability
Provides tracking services and debugging functions
Integrated in .NET Framework, powerful function
Database connection uses ADO.NET technology
General steps for designing a Web application
Operation steps for designing a Web application using VS 2005
S1: Create a new website
S2: Set the website location
S3: Add a web page
S4: Design a Web form
S5: Set the properties of the form and form controls
S6: Write a program
S7: Execute the Web application
S8: View Running results
Note, please refer to the textbook for details
(1) Generate Web application
Operation method: In the solution explorer window of Visual Studio .NET 2005, right-click the website name and select " Generate a website"
(2) Check whether the Web server is normal
If you want to publish to the local computer, you must check whether the local computer has installed IIS
Check whether IIS is working properly
Tables, records and fields
Relational database systems use the relational model as the way to organize data.
A table is a group of similar data stored in a common structure, similar to the table in daily life.
The table arranges related information into logical groups in rows and columns. Each row in the table is called a record.
Columns are called fields
Database
The database represents the data table as a collection of multiple tables, and defines the structure of the database by establishing relationships between tables
The so-called primary key refers to the unique identification of the table A field or a set of fields in a record. Primary keys do not allow duplicate values.
Foreign key refers to a field used to connect another table and serve as the primary key in another table.
Index
In relational databases, indexes are usually used to improve the speed of data retrieval.
Records in the table are stored in the physical order of input. When creating an index on the primary key or other fields, the database management system records the contents of the index fields in an index file in a specific order.
When retrieving data, the database management system first finds the location of the information from the index file, and then reads the data from the table.
Each index has an index expression to determine the order of the index. The index expression can be either a field or a combination of multiple fields.
Multiple indexes can be generated for a table, each index represents a sequence of processing data.
Relationship
The biggest benefit of a relational database is that it can avoid unnecessary duplication of data, that is, it can split a table containing duplicate data into several simple tables without duplicate data, and establish relationships between tables. relationship to retrieve records in related tables.
In the relationship between tables, it is customary to call the main table the parent table, and other tables connected through the relationship are child tables.
There may be 4 types of relationships between tables
One-to-one relationship: means that a record in the parent table matches at most one record in the child table, and vice versa;
One-to-many Relationship: refers to the records in the parent table that are related to multiple records in the child table. For example, for the customer table and the order table, each order is only related to one customer, and each customer can have multiple orders, so the customer table and the order table are a one-to-many relationship;
many-to-one relationship : Complementary to one-to-many, that is, multiple records in the parent table are related to one record in the child table;
Many-to-many relationship: refers to multiple records in the parent table and multiple records in the child table related.
SQL Introduction
SQL (Structured Query Language) language is a comprehensive, universal relational database language whose functions include query, manipulation, definition and control.
Currently, there are 3 versions of the SQL standard.
SQL-89
SQL-92
SQL3
Transact-SQL used by Microsoft SQL Server is expanded on the basis of the SQL-92 standard.
Composition of SQL
SQL is composed of elements such as commands, clauses, and operators. These elements are combined to form statements for creating, updating, and manipulating data.
SQL commands are divided into two categories: DDL (data definition language) commands and DML (data manipulation language) commands. DDL commands are used to create and define new databases, fields and indexes, mainly including statements: create, drop, alter. DML commands are used to create queries to sort, filter, and extract data from the database. They mainly include statements: select, insert, update, and delete. P258
SQL clauses are used to define the data to be selected or manipulated.
select statement
The function of the select statement is to retrieve data from an existing database.
from clauseSpecify the source of the data, that is, indicate which tables the records come from.
where clauseSpecifies the conditions to be met when selecting records.
The group by clause groups records.
The having clause determines which records are specifically displayed in the query with the group by clause. You can use the having clause to display groups that meet the specified conditions.
The order by clause sorts the records.
For statement examples, see P258-260
delete statement
The function of the delete statement is to delete records in one or more tables listed in the from clause and that meet the conditions of the where clause.
For example:
delete from Orders Where OrderId=16
insert statement
insert statement is used to add records to the table.
For example:
insert into Orders
(CustID,ProductID,OrderDate,SendDate,Qty)
values('2','5','2008-8-12','2008-8 -13',1)
update statement
update statement updates field values in a specific table according to a certain condition.
For example:
update Products set Price=8900 where Products.ProductId=3
ADO.Net Overview
ADO.NET is Microsoft’s latest and most powerful database access technology. Applications use ADO.NET can easily access and process data stored in various databases.
ADO.NET gathers many classes for data processing. These classes have powerful functions for data access and processing, such as indexing, sorting, browsing and updating.
ADO.NET is integrated in the .NET Framework and can be used in any computer language that supports .NET, such as C#.
ADO.NET mainly includes the System.Data namespace and its nested namespaces, as well as some special classes related to data access such as the system.Xml namespace.
Data Provider
Data Provider provides the connection between DataSet and database, and also includes a series of interfaces for accessing the database. Data from various data sources can be easily accessed through the application programming interface (API) provided by the data provider.
.NET data providers include the following:
SQL Server .NET data provider, used for Microsoft SQL Server data sources, from the System.Data.SqlClient namespace;
OLE DB .NET data Provider, used for OLE DB exposed data source data source, from the System.Data.OleDb namespace;
ODBC.NET data provider, used for ODBC exposed data source from the System.Data.Odbc namespace ;
Oracle .NET data provider for Oracle data sources, from the System.Data.OracleClient namespace.
Data Provider
.NET Data Provider has 4 core objects:
Connection object is used to establish a connection with the data source;
Commmand object is used to execute specified commands on the data source;
DataReader object Used to return a forward-only read-only data stream from the data source;
The DataAdapter object automatically transforms various operations on the data into the corresponding SQL statements of the data source.
DataSet
The core component of ADO.NET is DataSet.
You can think of a DataSet as an in-memory database. It is an independent dataset that does not depend on the database. Independent means that the DataSet is still available even if the data connection is disconnected or closed.
In ADO.NET, DataSet is specially used to process data obtained from data sources. No matter what the underlying data is, the same method can be used to operate data obtained from different data sources.
DataSet internally uses XML to describe data. XML is a data description language that is platform-independent and data-independent and can describe complex data relationships.
ADO.NET database operation process
First use the Connection objectConnect to the database;
If you execute a database execution command or stored procedure that does not require a return result, you can Using the Command object;
DataReader object is used to read forward-only and read-only data streams from the data source.
DataSet is a memory-resident representation of data that provides a consistent relational programming model that is independent of the data source. DataSet represents the entire data set, which contains tables, constraints, and relationships between tables.
Interaction with existing data sources is controlled through DataAdapter. The DataAdapter object is used to obtain data from the data source, populate the DataSet and tables and constraints, and submit changes to the DataSet back to the data source.
Use Connection object to access the database
Steps to connect to the database
(1) Define the connection string
Use SQL Server authentication:
Data Source=server name;Initial Catalog=database name; User ID =Username;Pwd=Password
Use Windows Authentication:
Data Source=Server name;Initial Catalog=Database name;
Integrated Security=True
(2) Create Connection object
SqlConnection connection = new SqlConnection(connString);
(3) Open the connection to the database
connection.Open( );
Use the Command object to access the database
Steps to use ExecuteNonQuery():
( 1) Create Connection object;
(2) Define sql statement;
(3) Create Command object;
(4) Execute ExecuteNonQuery() method;
(5) Process according to the returned result .
The above is the detailed content of Summary of conceptual systems in C#. For more information, please follow other related articles on the PHP Chinese website!