In those years, I am still studying C # Study Notes

Source: Internet
Author: User

C # is an object-oriented language with basic features of object-oriented, such as abstraction, encapsulation, inheritance, and polymorphism. Learning C # apart from some basic syntaxes, you have to learn some new features, such as generics, multithreading, collections, and reflection. Let's select some of them to learn!
I. Various devices in C #
A, C # constructor-Constructor
As follows: Copy codeThe Code is as follows: // constructor 1
Public Products (int id)
{
_ Id = id;
}
// Constructor 2. Use this to call constructor 1.
Public Products (int id, string Name, string Band)
: This (id)
{
_ ProductName = Name;
_ ProductBand = Band;
}

Static constructor-used to initialize the class. It does not display the called information. It will be called automatically when the class is accessed for the first time. It is used to initialize some basic information of the class rather than the object, but it is best not to use a static constructor. The Code is as follows:Copy codeCode: static Products () {}// static Constructor
Public Products (){}

B. Initialization tool-when there is no constructor with parameters, we can use the initialization tool to initialize the common attributes of the object.
As follows:Copy codeThe Code is as follows: // a List of products
List <Products> ListProduct = new List <Products> ()
{
New Products () {_ Id = 1, _ ProductName = "whc"}, // use {} to call the initialization tool to initialize Properties
New Products () {_ Id = 1, _ ProductName = "whc1", _ ProductBand = "ctbu "},
New Products () {_ Id = 1, _ ProductName = "whc2", _ ProductBand = "ctbu "}
};

C. Terminator
The Terminator is executed after the last activity of an object and before the termination of the program. When the terminal recycler is pulled, it finds the object with the Terminator and adds it to the end queue. After the thread traversal is complete, it calls the terminator of the object in the end queue to recycle resources.
Ii. Important knowledge in C #
A. Delegation and events
Delegate
C # pass a method as a parameter to other methods for use. The mode for implementing such a function is called delegate.
1. Delegate type: it is a strong type, because when declaring a delegate method, the specified parameter must pass the same type of parameters and number of parameters when calling this delegate.
2. Internal Mechanism of delegation: C # All delegates are inherited from System. Delegate, but we cannot inherit it to implement custom delegation. You can use the delegate keyword to define the delegation.
3. Definition of delegation: Use the delegate keyword
4. Delegation instantiation: defines a function of the same type as the delegate. It is passed as a delegate parameter and does not need to be instantiated using the new keyword. It can be inferred through delegation, in C #1.0, the new delegate (Method) must be used to pass the Method)
5. Use of delegation:Copy codeThe Code is as follows: class DelegateClass
{
// A generic delegate, which can be processed by different types of parameters
Public delegate void AlculateMethod <T> (T first, T second );
}
Class MehtodConllection
{
Public void AlculateAdd <T> (T first, T second)
{
String third = first. ToString () + second. ToString ();
System. Console. WriteLine (third );
}
Public void AlculateDelete (int first, int second)
{
System. Console. WriteLine (first-second );
}
Public void AlculateAddOther <T> (T first, T second)
{
String third = first. ToString () + "Hello Word" + second. ToString ();
System. Console. WriteLine (third );
}
}
Private static void _ Demo4 ()
{
// Set of methods
MehtodConllection mc = new MehtodConllection ();
// Generic delegation statement
DelegateClass. AlculateMethod <string> Demo = null;
// Add delegate Method
Demo + = mc. AlculateAdd <string>;
//
Demo + = mc. AlculateAddOther <string>;
// Call a method. All methods in the delegate can be executed.
Demo ("str", "sterte ");
}

Event
An event is a Special Delegate. When declaring a delegate, add an event keyword.
Steps:
1. Define the delegate type, which is equivalent to a class, such as: public delegate void ActionMethod ();
2. Define the event Delegate variable, which is defined by the delegate type in 1. For example, public event ActionMethod amd;
3. Call defined events and triggers, such:Copy codeThe Code is as follows: class Cat
{
// Define the delegate Method
Public delegate void ActionMethod ();
// Declare event Delegate
Public event ActionMethod amd;
// Trigger the event
Public void CatShout ()
{
System. Console. WriteLine ("it's called, and the event is triggered !!! ");
Amd ();
}
}

4. Add a method to the event and bind the method with the event for execution at the time of triggering, for example:Copy codeThe Code is as follows: private static void _ Demo15 (){
Cat cat = new Cat ();
HostPerson hp = new HostPerson ();
Mouse mouse = new Mouse ();
Cat. amd + = mouse. runing;
Cat. amd + = hp. WeekUp;
Cat. CatShout ();
}

5. Events finally triggered
B. Reflection and Characteristics
Reflection
1. Effect of reflection:
(1) access the metadata in the Assembly, for example, the method property modifier
(2) Use metadata to dynamically call Members and attributes of metadata at runtime, rather than binding at compilation.
2. Reflection refers to the process of checking the metadata in an assembly, listing the types and attributes of the Assembly, and calling the above members using some specific objects.
3. Use System. Type to access metadata
The Type metadata System. Type is an instance. This instance provides some methods to list metadata members. The main methods are as follows:
Type. name, Type. isPublic, Type. baseType, Type. getInterface (), Type. assemble, Type. getProperties (), Type. getMethod (), Type. getField (), Type. getCustomAttributes () and other attributes
(1) Use GetType () to get the metadata Type object (System. Type)
Example:
Category 1:Copy codeThe Code is as follows: class CustomClass
{
Private string Name = "Test ";
Public string _ Name = "Demo ";
Private int index {get; set ;}
Public int _ index {get; set ;}
Private void GetName ()
{
}
Public void Get_Name ()
{
}
}

Class 2: Both typeof and GetType () are used to obtain the type object.Copy codeThe Code is as follows: public void Exec ()
{
CustomClass cc = new CustomClass ();
// Obtain the Instance Object of the current type
Type type = cc. GetType ();
// Obtain the Instance Object of the current type using typeof
// Type type = typeof (CustomClass );
// Traverses public attributes instead of fields. Use GetProperties ()
Foreach (PropertyInfo property in type. GetProperties ())
{
// Obtain the attribute name.
System. Console. WriteLine (property. Name );
// Obtain the attribute type
System. Console. WriteLine (property. PropertyType );
// Obtain the reflection type, that is, the Class Name of the reflection object.
System. Console. WriteLine (property. ReflectedType );
// Obtain the member type, whether it is an attribute or a method
System. Console. WriteLine (property. MemberType );
}
System. Console. WriteLine ("------------------------------------------");
// Get the public method of the current object, including the Public attribute method get, set
Foreach (System. Reflection. MethodInfo method in type. GetMethods ())
{
// Method name
System. Console. WriteLine (method. Name );
// Member type
System. Console. WriteLine (method. MemberType );
}
}

Result:

(2) Obtain and set the attribute valueCopy codeThe Code is as follows: // set the attribute value
Property. SetValue (cc, 45, null );
// Obtain the attribute value
System. Console. WriteLine (property. GetValue (cc, null). ToString ());

(3) call the method Invoke () functionCopy codeThe Code is as follows: MethodInfo demo = type. GetMethod ("Get_Name ");
Demo. Invoke (cc, null );

Get the Get_Name method without parameters. If any parameter is null, it should be an array of parameters.
For example: // call an API with ParametersCopy codeThe Code is as follows: MethodInfo test = type. GetMethod ("GetName ");
String [] param = {"12 "};
Test. Invoke (cc, param );

Attribute)
1. features are used to describe or modify additional information of metadata, such as classes, attributes, and assembly.
2. Custom features inherited from the Attribute Class
As follows:Copy codeThe Code is as follows: class CustomAttribute: Attribute
{
Public CustomAttribute ();
Public customattrion (AttributeTargets validOn );
Public bool AllowMultiple {get; set ;}
Public bool Inherited {get; set ;}
Public AttributeTargets ValidOn {get ;}
}

Usage:Copy codeThe Code is as follows: [CustomAttribute (AttributeTargets. All)]
Class CustomClass
{
[Customattriple (AllowMultiple = true)]
[Custom (Inherited = true)]
Private string Name = "Test ";
Public string _ Name = "Demo ";
Private int index {get; set ;}
Public int _ index {get; set ;}
}

C. Use of extension methods and Lambda expressions
Extension Method
When you cannot modify a class, the extension method is a convenient way to add other methods to the class.
1. Definition of an extension method: the extension method uses the keyword "this" to bind a method to a member of the type (for example, class) pointed to by "this, so we can call this method through the object of this class. In MVC, the extension and HtmlHelper class are very useful, as shown in the following code:Copy codeThe Code is as follows: public static class PersonExtension
{
Public static void Extension (this PersonSingle ps, string name)
{
System. Console. WriteLine ("Name is" + name );
}
}

Add the Extension (string name) method to PersonSingle, and then you can call this method through the object.
PersonSingle class:Copy codeThe Code is as follows: public class PersonSingle
{
Public void Show ()
{
System. Console. WriteLine ("PersonSingle Method !!! ");
}
}

Test:Copy codeThe Code is as follows: private static void _ Demo16 ()
{
PersonSingle ps = new PersonSingle ();
Ps. Show ();
Ps. Extension ("whc ");
}

2. The access permission of the extension method must be the same as that of the extended class. Here, the access permission is public.
3. The extension method is a static method written in a static class.
Lambda expressions
Lambda expressions are more concise than anonymous functions. They are classified into two types: Statement lambda and expression lambda.
1. Statement Lambda: A simplified Syntax of an anonymous method. It does not contain the delegate keyword. You only need to use the lambda operator =>, which is a statement block.
Example:Copy codeThe Code is as follows: Demo + = (string first, string second) =>
{
System. Console. WriteLine ();
};

2. Expression Lambda: an expression rather than a statement Block
Example:Copy codeThe Code is as follows: Demo = (first, second) => first. ToString ();

3. external variables can be used in Lambda expressions
Summary
C # in those years, I made some notes. Most of these articles are directly copied from the notes. Of course, there are many other notes that will be added next time. This article will recall the days of my years of study.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.