.NET platform and C# programming

.NET platform and C# programming

1, Drill down to. NET framework

1. Overview of microsoft.net framework

The strategic goal of. NET is to get any information on the network through. NET services at any time, anywhere and with any tool, and to enjoy the convenience and joy brought by the network. The. NET framework, which was released later, is the core foundation for developing. NET applications.

2... NET framework architecture

The. NET framework has two main components: CLR and FCL. CLR is the foundation of the. NET framework. FCL is a comprehensive collection of object-oriented reusable types, which can be used to develop not only traditional command-line applications, but also WinForms applications and ASP.NET based applications.

  1. WPF: WPF is one of the core development libraries of Microsoft Vista. It is not only a graphics engine, but also brings a revolution to the development of Windows applications.
  2. WCF: WCF unifies Web services,. NET Remoting and other technologies into a single service-oriented programming model to achieve real distributed computing.
  3. WF: WF is a widely used workflow framework, and it is designed for scalability from bottom to top.
  4. LINQ: LINQ extends powerful query to the syntax of C ා and Vista basic. Net, which enables software developers to use object-oriented syntax to query data, and to write LINQ query for various data sources such as SQL Server database, XML document, ADO.NET data set, etc.

CLR

The common language runtime (CLR) is the engine in the core of managed code execution. The runtime provides various services for managed code, such as cross language integration, code access security, object lifetime management, debugging and analysis support. It is the core of the entire. NET framework and provides a managed code execution environment for. NET applications. It is actually a piece of agent code that resides in memory and is responsible for the code management of the application during the whole execution. CLR consists of two parts: CLS (common language specification) and CTS (common type system).

. NET compilation technology

In order to achieve the strategic goal of cross language development and cross platform,. NET is not compiled into local code, but into Microsoft intermediate code (MSIL). It will be converted from JIT compiler to machine code.

FCL

Another important part of the. NET framework is FCL, the framework class library. These libraries enable us to develop software. FCL provides calls to system functions, and is the basis for building. NET applications, components, and controls. Through the flexible use of these libraries, the development work will be more convenient.

. NET control core class library and its functions

System: this named control contains all other namespaces.

System.Collections.Generic: supports generic operations.

System.Io: supports operation on files.

System,Net: support the programming of network protocol.

System.Data: provides access to classes that represent ADO.NET structures.

System.Windows.Forms: used to develop Windows applications.

System.Drawing: support GDI + basic graphic operation.

3. Object oriented review

Classes and objects

  • The process of generalizing objects into classes is to generalize the commonness of objects.
  • Based on classes, the process of materializing state and behavior into objects is called instantiation.
  • For the properties of a class, we access and set them through get and set accessors to ensure the security of the data in the class. There are three types of property accessors
  • Write only property: contains only set accessors
  • Read only property: contains only get accessors
  • Read write property: contains both set and get accessors

encapsulation

Encapsulation is the combination of abstract data and behavior (or function) to form an organic whole, that is, the combination of data and source code to operate data to form a "class", in which data and functions are members of the class.
The purpose of encapsulation is to enhance security and simplify programming. Users do not need to know the specific implementation details, but only use the class members with specific access rights through the external interface.
The meaning of encapsulation in network programming is that when the application program transmits data with TCP, the data is sent into the protocol stack, and then one by one through each layer until it is sent into the network as a string of bit streams, in which each layer adds some headers to the received data.

Encapsulation brings us the following benefits

  • Ensure data security.
  • Provide clear external interface.
  • The internal implementation of a class can be modified without affecting other classes.

Encapsulating fields as attributes is a way of encapsulating, and private methods of classes are also a way of encapsulating.

Class diagram

Class diagram consists of many (static) descriptive model elements (such as classes, packages, and their relationships, which are interconnected with their contents). Class diagrams can be organized in (and belong to) packages, showing only the relevant content in a specific package. Class diagram is the most commonly used UML diagram, which shows classes, interfaces and their static structure and relationship; it is used to describe the structural design of the system. The most basic element of a class diagram is a class or interface.
Class diagram is mainly used in the analysis and design stage of object-oriented software development to describe the static structure of the system. The class diagram shows all the entities of the built system, the internal structure of the entities and the relationship between the entities. That is, the class diagram contains the class abstracted from the user's objective world model, the internal structure of the class and the relationship between the class and the class. It is the basis of building other design models. Without class diagram, there will be no object diagram, state diagram, collaboration diagram and other UMI. Dynamic model diagram, which can not represent the dynamic behavior of the system. Class diagram is also the starting point and basis of object-oriented programming.
Class diagram is used to describe the classes contained in the system and their relationships, and help people simplify the understanding of the system. It is an important product of system analysis and design stage, and also an important model basis for system coding and testing.

2, In depth C data type

1. Value type and reference type

Summary

In order to improve the development efficiency, C is very similar to the data type improved by Java

Common data types Java C# Give an example
integer int int Age
float float float achievement
Double precision type double double PI
Character string String string Home address
Boolean type boolean bool Minority name family or not
Enumeration type enum enum colour

In the table, you can see that data types can be divided into two types according to the storage mode: value type and reference type.

Value type

The value type comes from the System.ValueType family. Each object of value type has an independent memory area for storing its own value. The memory area where the value type data is located is called Stack. As long as you modify it in your code, you save the value in its memory area. Value types mainly include basic data types and enumeration types.

static void Main(string[] args)
        {
            int heightZhang = 170;
            int heightLi = heightZhang;
            Console.WriteLine("Last year--Zhang Hao is tall:" + heightZhang + ",Li Ming's height is:" + heightLi);
            heightLi = 180;
            Console.WriteLine("This year--Zhang Hao is tall:" + heightZhang + ",Li Ming's height is:" + heightLi);
        }

For the value type, different variables will allocate different storage space, and the value of the variable is stored in the storage space. Assignment passes the value of a variable. Changing the value of one variable does not affect the value of another.

reference type

The reference type comes from the System.Object family. In C, the reference type mainly includes array, class and interface.

static void Main(string[] args)
        {
            int[] infoZhang = new int[] { 170, 60 };
            int[] infoLi = infoZhang;
            Console.WriteLine("Last year--Zhang Hao is tall:" + infoZhang[0] + "The weight is:"+ infoZhang[1] + ",Li Ming's height is:" + infoLi[0]+"The weight is:"+ infoLi[1]);
            infoLi[0] = 180;
            infoLi[1] = 70;
            Console.WriteLine("Last year--Zhang Hao is tall:" + infoZhang[0] + "The weight is:" + infoZhang[1] + ",Li Ming's height is:" + infoLi[0] + "The weight is:" + infoLi[1]);
        }

As you can see, the identifier infoZhang is just a reference, and it only refers to the array created in memory. If we compare the stored objects (that is, arrays) to balloons, our reference variables (that is, infoZhang) are a line. For reference type, assignment is to pass the reference of the original object to another reference. For an array, when an array reference is assigned to another array reference, the two references point to the same array, that is, to the same block of storage space.

static void Main(string[] args)
        {
            int[] infoZhang = new int[] { 170, 60 };
            int[] infoLi = new int[2];
            Console.WriteLine( "Before replication--Li Ming's height is:" + infoLi[0] + "The weight is:" + infoLi[1]);
            //Array replication
            for (int i = 0; i < infoZhang.Length; i++)
            {
                infoLi[i] = infoZhang[i];
            }
            Console.WriteLine("Last year--Zhang Hao is tall:" + infoZhang[0] + "The weight is:" + infoZhang[1] + ",Li Ming's height is:" + infoLi[0] + "The weight is:" + infoLi[1]);
            infoLi[0] = 180;
            infoLi[1] = 70;
            Console.WriteLine("Last year--Zhang Hao is tall:" + infoZhang[0] + "The weight is:" + infoZhang[1] + ",Li Ming's height is:" + infoLi[0] + "The weight is:" + infoLi[1]);
        }

Breakdown value type and reference type

The int type we use is the value type, and the array is the reference type. The value types and reference types contained in C are shown in the following table

category Basic data type describe
Value type Integer: int
long
Floating point: flo
double: double
Character type: char
Bool: bool
Enumeration type Enumeration: enum
structure type Structure: struct
reference type class Base class: System.Object
string: string
Custom class: clas
Interface interface: interface
array Array: int [], string []

2. structure

Definition

Access modifier struct name
{
	/ / structure
}

The definition of structure has the following characteristics

  • There can be fields or methods in the structure.
  • When defined, fields in the structure cannot be assigned.

Use

The structure is similar to the class. When using structures, pay attention to the following aspects.

  • You can define the objects of the structure directly without new.
  • After you declare an object of a structure, you must assign an initial value to the members of the structure.
public class Student
    {
        public int _id;
        public int _age;
        public void Show()
        {
            Console.WriteLine("ID: {0}\n Age:{1}",_id,_age);
        }
        static void Main(string[] args)
        {
            Student stu = new Student();
            stu._id = 1001;
            stu._age = 20;
            stu.Show();
        }
    }

Using experience

Structure is a value type. Declaring a structure variable stores a new copy of the structure, that is to say, the system needs to open up a new storage space, so the more the structure uses, the more storage space it consumes. So when objects need to be represented with fewer fields, they can be implemented with structures.

3. Packing and unpacking

We say that data types can be divided into value types and reference types according to the storage mode, and they can still be converted to each other. The process of converting a value type to a reference type is called boxing, and vice versa.

static void Main(string[] args)
        {
            int i = 123;
            object o = i;
            i = 456;
            Console.WriteLine("The value of the value type is{0}",i);
            Console.WriteLine("The value of the reference type is{0}",o);
        }
static void Main(string[] args)
        {
            int i = 123;
            object o = i;
            int j = (int)o;
        }

In the actual development, unnecessary packing and unpacking should be minimized as much as possible, because the two storage methods are different, and the performance loss during conversion is large.

4. Different types of parameter transfer

  • When a value type parameter is passed using the value method (without ref decoration), the modification of the parameter in the method is not preserved.
  • When a reference type parameter is passed in value mode (without ref decoration), the modification of the parameter in the method is not preserved.
  • When a value type or a reference type parameter is passed by reference (decorated with ref), the modification of the parameter in the method is retained.

3, Using collections to organize related data

1.ArrayList

ArrayList is very similar to array. Some people call it array list. ArrayList can be maintained dynamically. We know that the capacity of array is fixed, while the capacity of ArrayList can be expanded as needed, and its index will be reallocated and adjusted according to the expansion of the program. ArrayList provides a series of methods to access, add, and delete elements in it.

The Areyist class belongs to the System.Coleliens namespace, which contains interfaces and classes that define collections of various objects. ArrayList is a kind of collection, so you must introduce the System.Coleliens namespace before using the ArrayList class.

The common properties and methods of ArrayList are as follows:

Attribute name Explain
Count Get the actual number of elements in ArrayList
return type Method name Explain
Int Add(Object value) Add object to the end of ArrayList
void RemoveAt(int index) Remove element at ArrayList specified index
void Remove(Object value) Remove specific objects from ArrayList
void Clear() Remove all elements from ArrayList

Add data

static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add(16);
            list.Add("Dong Shi Hao");
        }

Return value: the value is an int type used to return the index of the added element.

Parameter: if the elements added to ArrayList are of value type, they will be boxed and converted to Object reference type, and then saved. Therefore, all elements in the ArrayList are references to objects.

Access single element

static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add(16);
            list.Add("Dong Shi Hao");
		   Console.WriteLine(list[0].ToString());
        }

The method of getting an element from ArrayList is the same as that of array, and it is also accessed through index. The index of the first element in ArrayList is 0. It should be noted that since the ArrayList will be converted to Object type, they must be converted back to the original data type when accessing these elements.

Traversing elements in ArrayList

static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add(16);
            list.Add("Dong Shi Hao");
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine("for Cycle output:"+list[i]);
            }
            foreach(object obj in list)
            {
                Console.WriteLine("foreach Cycle output:"+obj);
            }
            Console.WriteLine("Length:"+list.Count);
            Console.WriteLine("Name:"+list[1]);
        }

Delete elements in ArrayList

static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add(16);
            list.Add("Dong Shi Hao");
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine("for Cycle output:"+list[i]);
            }
            foreach(object obj in list)
            {
                Console.WriteLine("foreach Cycle output:"+obj);
            }
    	    list.RemoveAt(0);
    		list.Remove("Dong Shi Hao");
    		list.Clear();
            Console.WriteLine("Length:"+list.Count);
        }

2.Hashtable

HashTable, also known as hash table, is a data structure directly accessed according to key value (i.e. key value pair). That is, it accesses records by mapping keys to a location in the table to speed up lookup. You may be wondering how it speeds up the search? The next section has instructions! This mapping function is called hash function, and the array of records is called hash table.

Hashtable also belongs to the System.Collections namespace, and each of its elements is a key / value pair.

Attribute name Explain
Count Get the number of real key / value pairs in the Hashtable
Keys Get the collection of keys contained in the Hashtable
Values Get the set of values contained in the Hashtable
return type Method name Explain
Void Add(Object key,Object value) Add an element with the specified key and value to the Hashtable
void RemoveAt(Object key) Remove an element with a specific key specified by the Hashtable
void Clear() Remove all elements from the Hashtable

Add data

static void Main(string[] args)
        {
            Hashtable ha = new Hashtable();
            ha.Add(1, "Zhang San");
            ha.Add(2, "Wang Xue");
        }

Get elements of Hashtable

static void Main(string[] args)
        {
            Hashtable ha = new Hashtable();
            ha.Add(1, "Zhang San");
            ha.Add(2, "Wang Xue");
            Console.WriteLine(ha[1]);
        }

Traversing elements in a Hashtable

static void Main(string[] args)
        {
            Hashtable ha = new Hashtable();
            ha.Add(1, "Zhang San");
            ha.Add(2, "Wang Xue");
            Console.WriteLine(ha[1]);
            foreach(Object obj in ha.Values)
            {
                Console.WriteLine((string)obj);
            }
            foreach(DictionaryEntry entry in ha)
            {
                Console.WriteLine(ha.Keys);
                Console.WriteLine(ha.Values);
            }
        }

Delete elements in Hashtable

static void Main(string[] args)
        {
            Hashtable ha = new Hashtable();
            ha.Add(1, "Zhang San");
            ha.Add(2, "Wang Xue");
            Console.WriteLine(ha[1]);
            foreach(Object obj in ha.Values)
            {
                Console.WriteLine((string)obj);
            }
            foreach(DictionaryEntry entry in ha)
            {
                Console.WriteLine(ha.Keys);
                Console.WriteLine(ha.Values);
            }
            ha.Remove(1);
            ha.Clear();
        }

3. Generic set list < T >

There are many generic collection classes defined in the System.Collections.Generic namespace, which can be used to replace the previous ArrayList and Hashtable.

List<T> Object name = new List<T>();

T in "< T >" can constrain the element types in the collection. T indicates the element types managed in the collection. With the generic set list < T >, it can constrain the data types of set elements, so there will be no more type conversion problems.

Similarities and differences List<T> ArrayList
Difference Type constraints on saved elements Any type can be added
Add / read value type elements do not need to be boxed or unboxed Add / read value type elements need to be boxed and unboxed
Common ground Accessing elements in a collection by index
Add elements the same way
Delete elements the same way

4. Generic set dictionary < K, V >

A generic set dictionary < K, V > of CNOOC in C, which has all the features of generics, price difference type constraint at compile time, no conversion is needed to get type, and its storage mode is similar to Hashtable, and it is also saved to elements through Key/Value (Key/Value)

Dictionary<K,V> Object name = new Dictionary<K,V>();
static void Main(string[] args)
        {
            Dictionary<string, string> va = new Dictionary<string, string>();
            va.Add("16", "Dong Shi Hao");
            va.Add("66", "Zhang San");
            foreach(Object sa in va.Keys)
            {
                Console.WriteLine(sa);
            }
            foreach(Object str in va.Values)
            {
                Console.WriteLine(str);
            }
            va.Add(null, "123");//Operation error
        }
Similarities and differences Dictionary<K,V> Hashtable
Difference Type constraints on saved elements Any type can be added
Add / read value type elements do not need to be boxed or unboxed Add / read value type elements need to be boxed and unboxed
Common ground Accessing elements in a collection by index
Add elements the same way
Delete elements the same way

5. generic class

public  class  Class name<T>
{
	//........
}

T refers to the type parameter, which represents the specific data type. It can be a class type or a basic data type.

class ComboBoxItem<T>
        {
            private string _itemText;   //Displayed text
            public string ItemText
            {
                get { return _itemText; }
                set { _itemText = value; }
            }
            private T _itemValue;   //Actual object
            public T ItemValue
            {
                get { return _itemValue; }
                set { _itemValue = value; }
            }
        }
        //Create ComboBox items and determine the data types supported by generic classes at runtime
            ComboBoxItem<SE> itemJack = new ComboBoxItem<SE>();
            itemJack.ItemText = jack.Name;
            itemJack.ItemValue = jack;
            ComboBoxItem<SE> itemJoe = new ComboBoxItem<SE>();
            itemJack.ItemText = joe.Name;
            itemJack.ItemValue = joe;

            //Create Items
            List<ComboBoxItem<SE>> items = new List<ComboBoxItem<SE>>();
            items.Add(itemJack);
            items.Add(itemJoe);

            //Binding Items
            this.cmbEngineers.DataSource = items;
            this.cmbEngineers.DisplayMember = "ItemText";
            this.cmbEngineers.ValueMember = "ItemValue";

Advantages of generics

  • High performance. The data of common collection needs boxing and unboxing, while generics do not need type conversion.
  • Type safety. The generic collection has type constraints on the objects it stores, not that the types it allows to store cannot be added to the generic collection.
  • Realize code reuse. Generics are equivalent to templates. Because they support arbitrary data types, developers do not have to write a set of methods for each specific data type, so they have great reusability. Generic programming is one of the main technologies in the future.

4, Methods of deep class

1. Constructor

Class constructor is a special method in a class. It has the following characteristics:

  • The method name is the same as the class name.
  • No return value type.
  • It mainly completes the initialization of objects.

2. Parameterless constructor

By default, the system assigns a parameterless constructor to the class, and there is no method body. We can also customize a parameterless constructor to assign values to the properties of the class in the method body of the parameterless constructor.

Access modifier class name ()
{
	/ / method body
}
class Program
    {
        public class SE
        {
            private string name;
            public string Name
            {
                get { return name; }
                set { name = value; }
            }
            private int age;
            public int Age
            {
                get { return age; }
                set { age = value; }
            }
            private string gender;
            public string Gender
            {
                get { return gender; }
                set { gender = value; }
            }
            private string id;
            public string ID
            {
                get { return id; }
                set { id = value; }
            }
            private int popularity;
            public int Popularity
            {
                get { return popularity; }
                set { popularity = value; }
            }

            internal string SayHi()
            {
                throw new NotImplementedException();
            }
            public SE()
            {
                this.ID = "000";
                this.Age = 20;
                this.Name = "Anonymous person";
                this.Gender = "male";
                this.Popularity = 0;
            }
        }
        static void Main(string[] args)
        {
            SE se = new SE();
            Console.WriteLine(se.SayHi());
        }
    }

Through the above examples, we can find that there is an obvious disadvantage in assigning default values to attributes in parameterless constructors, that is, the attribute values after object instantiation are fixed, so in order to meet the needs of object diversification, we have to modify the code to assign new values to attributes. So there is a constructor with parameters.

3. Constructor with parameters

Access modifier class name (parameter list)
{
	/ / method body
}
class Program
    {
        public class SE
        {
            private string name;
            public string Name
            {
                get { return name; }
                set { name = value; }
            }
            private int age;
            public int Age
            {
                get { return age; }
                set { age = value; }
            }
            private string gender;
            public string Gender
            {
                get { return gender; }
                set { gender = value; }
            }
            private string id;
            public string ID
            {
                get { return id; }
                set { id = value; }
            }
            private int popularity;
            public int Popularity
            {
                get { return popularity; }
                set { popularity = value; }
            }
            internal string SayHi()
            {
                throw new NotImplementedException();
            }
            public SE(string id,string name,int age,string gender,int popularity)
            {
                this.ID = id;
                this.Name = name;
                this.Age = age;
                this.Gender = gender;
                this.Popularity = popularity;
            }
        }
        static void Main(string[] args)
        {
            SE se = new SE("112", "AI edge Cheng", 25, "male", 100);
            Console.WriteLine(se.SayHi());
        }
    }

Obviously, a constructor with parameters is more flexible. It dynamically controls the characteristics of an object through parameters.

4. Implicit constructor

When a constructor is not written for a class, the system will automatically assign a parameterless constructor to the class, which is called an implicit constructor. C ා there is a rule that once a class has a constructor, it will no longer automatically assign the constructor.

5. Method overload

Method overloading refers to a technology that a method with the same name and different parameters in the same class can be called by selecting a method matching it to perform operations according to the form of arguments.

Different parameters here refer to the following situations:

  1. Different types of parameters

  2. The number of parameters is different

  3. The number of parameters is the same, and their order is different

Note: the system will consider two cases of the same method. Such two methods cannot be in the same class, or the system will report an error.

  1. Two methods with different return types and the same method name and parameter number, order and type

  2. Two methods with the same return type, the same number, order and type of method name and parameter, but different parameter names

class CompSalary
    {
        public static void Pay(PM pm)
        {
            float money = pm.BasePay + pm.MgrPrize + pm.Bonus;
            Console.WriteLine("Salary of Project Manager:"+money);
        }
        public static void Pay(SE se)
        {
            float money = se.BasePay + se.MeritPay;
            Console.WriteLine("Programmer's salary:" + money);
        }
        static void Main(string[] args)
        {
            SE se = new SE("112", "AI edge Cheng", 25, "male", 100);
            se.BasePay = 4000;
            se.MeritPay = 3000;

            PM joe = new PM("890", "Steve Jobs", 50, "male", 10);
            joe.BasePay = 8000;
            joe.MgrPrize = 4000;
            joe.Bonus = 2000;

            CompSalary.Pay(se);
            CompSalary.Pay(joe);
            Console.ReadLine();
        }

    }

The most important function of overloading is to save the effort of naming methods. The method overloading technique can avoid the trouble of naming, and can make callers call directly without judging the method name.

6. Object interaction

Each class has its own features and functions, which we encapsulate as properties and methods. Objects interact with each other through properties and methods. It can be considered that the parameters and return values of methods are messages passed between objects.

public class Television
    {
        private Boolean isOn = false;
        public void Open()
        {
            if (isOn)
            {
                Console.WriteLine("The TV is on!");
            }
            else
            {
                Console.WriteLine("TV on successfully!");
                isOn = true;
            }
        }
        public void TurnOff()
        {
            if (isOn)
            {
                Console.WriteLine("shutting down.....");
                isOn = false;
            }
            else
            {
                Console.WriteLine("The TV is off!");
            }
        }
        public void Change(string channelNo)
        {
            if (isOn)
            {
                Console.WriteLine("Switching to{0}platform", channelNo);
            }
        }
    }
public class RemoteControl
    {
        public void TurnOn(Television tv)
        {
            tv.Open();
        }
        public void TurnOff(Television tv)
        {
            tv.TurnOff();
        }
        public void ChangeChannel(Television tv)
        {
            Console.WriteLine("Please enter the channel number:");
            string channelNo = Console.ReadLine();
            tv.Change(channelNo);
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            RemoteControl control = new RemoteControl();
            Television tv = new Television();
            control.TurnOn(tv);
            control.ChangeChannel(tv);
            control.TurnOff(tv);
            Console.ReadLine();
        }
    }

The above example shows us the interaction process of remote control object and TV object. It can be seen that the interaction between objects is mainly realized by parameter passing, method calling and attribute operation. In object-oriented programs, objects interact with other objects by exposing methods and properties. It can be considered that the parameters and return values of methods are messages passed between objects.

Published 7 original articles, won praise 1, visited 314
Private letter follow

Tags: Programming network Attribute Windows

Posted on Thu, 13 Feb 2020 04:57:34 -0500 by MentalMonkey