C # Basics

Source: Internet
Author: User
Notes from "C # graphic tutorial"

Each. CS file must contain at least one class with the same file name.

Destructor: performs operations to clear or release unmanaged data before the class instance is destroyed.
Each class can have only one destructor;
Parameters are not allowed;
Cannot contain access modifiers.

Virtual method/overwrite method (when you need to override some methods of the base class in the derived class)
Virtual/override

Access modifier:
Public
Private class (default)
The derived classes in the same namespace of protected can be accessed.
Internal can be accessed anywhere in the same namespace
Protected internal or

Abstract Member: Abstract
Cannot be virtual Abstract
Abstract implementation must be override

Sealed: it can only be used as an independent class and cannot be used as a base class.

Static class: all members are marked as static. They cannot inherit and cannot create instances;

Extension Method: public static double average (this mydata. md)

External Methods: they are not implemented in declarations. They are often written in languages other than C.
Public static extern int func (INT size, stringbuilder BUF );

String: specification/verbatim (prefixed)

The Left shift is equivalent to the Npower of 2; the right shift is equivalent to the Npower of 2;

User-Defined type conversion:
Implicit conversion: Implicit
Explicit conversions: explicit

Operator overload:
Public static limitedint operator + (limitedint X, Double Y ){}

Typeof OPERATOR:
Type T = typeof (someclass );
GetType/tostring/equals/gethashcode

The number has no Boolean meaning in C.

Using alias command:
Using syst = system;
Using SC = system. Console;

Catch clause:
Catch {}
Catch (type ){}
Catch (type instid ){}

Throw an exception: Throw exceptionobject;


Structure

The class is the reference type and the structure is the value type;

The structure is implicitly sealed and cannot be derived;
Structure replication: Copies values from one structure to another. When copying class variables, only references are copied.
A predefined non-parameter constructor exists for each structure and cannot delete or redefine methods.
You cannot create a new struct, or use the value of a data member until it is explicitly set.
Field Initialization is not allowed.
The allocation structure requires less consumption than the instance for creating a class.

Enum trafficlight: Long
{
Green = 10,
Yellow, // The value is 11
Red // The value is 12.
}
Value Type: only one type of member is named as an integer constant;
Each Enumeration type is an underlying Integer type. The default value is int.

Array (reference type): Once created, the size is fixed. C # does not support dynamic arrays.
Objects inherited from system. Array
Rank dimension
Length element count
Int [] intarr = new int [] {10, 20 };
Foreach (INT item in ARR ){}

Array covariant: You can assign an object to an array element even if it is not the base type of the array.
An array is a reference type array.

Clone method:
An array of the clone Value Type generates two independent arrays;
Cloning an array of the reference type generates two arrays pointing to the same object.

List
Lists are more commonly used than arrays because lists are more flexible.
The Declaration List format is as follows:
List <datatype> <var Name> = new list <datatype> ();
List <int> intlist = new list <int> ();
Other data structures: queue, Dictionary (implementation of hash tables), hash set, read-only set, and tuples (. NET 4 +)

An object that contains an ordered method (Instance/static) list with the same signature and return value type.

When a delegate is called, it calls every method in the list.

Delegation is object-oriented and type-safe.

A delegate is a type like a class. It must be declared before being used to create variables and types.

Delegate void MYDEL (int x );

The return type and signature specify the form of methods accepted by the delegate.

The delegate declaration differs from the method declaration in that it starts with the delegate keyword; there is no method subject.

MYDEL devvar = new MYDEL (myinstobj. mym1); // create a delegate and save the reference

Or MYDEL devvar = myinstobj. mym1; // There is an implicit conversion between the method name and its delegate type

MYDEL Dela = myinstobj. mym1;
MYDEL delb = sclass. otherm2;
Mydel delc = Dela + delb; // combined call list

The delegate is constant and will not be changed after the delegate object is created.

MYDEL delvar = Inst. mym1; // create and initialize
Delvar + = SCL. m3; // Add Method
Delvar-= SCL. m3; // The removal method.

If the call list is empty, the delegate is null;
An exception is thrown when an attempt is made to call an empty delegate;
It is ineffective to try to delete methods that do not exist in the delegate;
-= Remove the first matching instance;

Delvar (55); // call the delegate

The value returned by the last method is the value returned by the delegate call. The return values of other methods are ignored.

Call a delegate with a reference (REF) parameter. The parameter value changes based on the return values of one or more methods in the call list. When you call the next method in the delegate list, the new value (not the initial value) of the parameter is passed to the next method.

The anonymous method is an inline declaration method during delegate initialization.
Otherdel del = delegate (int x) {return x + 20 ;};
The return value cannot be explicitly declared, but the behavior of the Code itself must match the return type of the delegate by returning a value of the same type as the return type of the delegate.
If the parameter list of the delegate Declaration contains the Params parameter, the Params keyword is ignored by the parameter list of the anonymous method.

Lambda expressions
MYDEL del = delegate (int x) {return x + 1 ;}; // anonymous method
MYDEL lel1 = (int x) =>{ return x + 1 ;}; // expression
MYDEL lel2 = (x) => {return x + 1 ;}; // expression
MYDEL lel3 = x =>{ return x + 1 ;}; // expression
MYDEL lel4 = x => x + 1; // expression

The event is actually a simplified delegate for special purposes. The method registered to the event will be called when the event is triggered.

Trigger event: term used to call or trigger an event. When an event is triggered, all methods registered with it are called in sequence.
Publisher: the class or structure used to make events visible to other classes or structures.
Subscriber: associates an event with the class or structure registered by the publisher.
Event Handler: the method used to register an event. It can be in the class or structure where the event is located, or in different classes or structures.

The event contains a private delegate.

Declare events
Public event eventhandler elapsed;

The event is a member, not a type. Implicit automatic Initialization is null.

Public event eventhandler elapsed;
Private void ononesecond (Object source, eventargs ARGs)
{
If (elapsed! = NULL)
{
Elapsed (source, argS );
}
}

The publisher class has an event as a member.
Class contains the code to trigger the event.

Standard event usage
Public Delegate void eventhandler (Object sender, eventargs E );

To pass data to the second parameter of your event handler and comply with standard conventions, You need to declare a custom class derived from eventargs.
Use custom delegate
Public Delegate void mytceventhandler (Object sender, mytceventargs E );
Public event eventhandler <mytceventargs> elapsed;

The interval attribute of system. Timers. Timer, which specifies the number of milliseconds between trigger events.

The + = and-= operators are the only operators allowed by events. These operators have predefined behaviors. We can modify these operators. It is implemented through the event accessors.
Public event eventhandler elapsed
{
Add {...}
Remove {...}
}

An interface indicates a group of function members without the reference type of the members. Class and structure can implement interfaces.
Public interface icomparable
{
Int compareto (Object OBJ );
}

The interface declaration can have any access modifier, but the interface members are implicitly public and explicit.

If the class inherits from the base class and implements the interface, the base class name in the base class list must be placed before any interface.
Class derived: mybaseclass, ienumerable, ienumerator {}

You cannot directly access the interface through a member of a class object. You can forcibly convert the Class Object Reference to the interface type to obtain the reference pointing to the interface. With the interface reference, you can use the point number to call the interface method.

As Operator
Ilivebirth B = A as ilivebirth;
If an interface is implemented, a reference pointing to the interface is returned;
If no interface is implemented, null is returned.

If a class implements multiple interfaces, some of these interfaces have members of the same signature and return type. Class can implement a single member to satisfy all interfaces that contain duplicate members.

The class implementing the interface can inherit the implemented code from its base class.

The explicit interface member implementation is declared using a limited interface name, which consists of the interface name, the member name, and the dot separator between them. It must always be accessed through interface references.

Interfaces can also be inherited from one or more interfaces. A class can inherit only one parent class.

For conversion of signed types, the extra high position is filled with the symbol bit of the source expression.

Packing: convert any value type to the object type/system. valuetype type;
Unboxing: Convert the boxed value to the original type.

Overflow detection context. If it is lost, an overflowexception exception is thrown.
OPERATOR:
Checked (expression)
Unchecked (expression)
Statement: (nested)
Unchecked
{
...
Checked
{
...
}
}

It is important to know how to handle the conversion in case of data loss.
Double to integer: if the result value is not within the range of the target type, overflowexception is thrown;
Double to float: If the value is too small and cannot be expressed as float, the value is set to positive or negative 0. If the value is too large and cannot be expressed as float, it is set to positive or negative infinity.
Float or double to decimal: If the value is too large and cannot be expressed as decimal, it is set to 0. If it is too large, an overflowexception exception is thrown.
Decimal to float or double: always successful, but may lose precision.

Forced conversion of the parent class to a subclass will cause invalidcastexception, but it is not a compilation error.

Effective explicit reference Conversion
1. Conversion from the category class to the base class;
2. The source reference is null;
3. The actual data referenced by the source can be implicitly converted safely.

Packing and conversion
Is a value that accepts the value type. Based on this value, a complete reference type object is created on the stack and an implicit conversion of the Object Reference is returned.

Int I = 12;
Object o = NULL;
O = I;
Create an int type object in the memory;
Copy the value of I to this object;
Return the reference of the int object to I;

Any value types of valuetypes can be implicitly converted to object, system. valuetype, or interfacet (if valuetypes implements interfacet ).

Binning Conversion
Is the process of converting the boxed object back to the value type.
An invalidcastexception is thrown when you try to unpack a value of Non-primitive type.

User-Defined conversions: In addition to standard conversions, we can also define implicit and explicit conversions for classes and structures.

Public Static Implicit operator targettype (sourcetype identifier)
{
...
Return objectoftargettype;
}
Convert person to int
Public Static Implicit operator int (person P)
{
Return P. Age;
}

Is Operator
Expr is targettype; // return bool
If the expr expression can be successfully converted to the target type in the following way, the return value is true.
Reference conversion, packing conversion, and unpacking conversion. Cannot be used for custom conversions.

As Operator
Similar to the forced type conversion operation, it does not throw an exception. If the conversion fails, it sets the target reference to null instead of throwing an exception.
Expr as targettype;
Expr source expression; target type of targettype, which must be a reference type;

It can only be used for reference conversion and packing conversion, and cannot be used for custom conversion or conversion to value type.

Generic generics allow us to declare code for Type parameterization, And we can instantiate it with different types. That is to say, we can use "type placeholders" to write code, and then provide the actual type when creating the class instance.

Generic declaration instance:
Class mystack <t>
{
Int stackpointer = 0;
T [] stackarray;
Public void push (t x ){....}
Public t POP (){...}
}
T represents a placeholder of the type, not necessarily a letter T. It can be any identifier. T is also called a type parameter.

Class someclass <T1, T2>
{
Public T1 somevar = new T1 ();
Public T2 othervar = new T2 ();
}
Someclass <short, int> myinst;
Myinst = new someclass <short, int> ();
VaR mysc = new someclass <short, int> ();
Use the VaR keyword to make the compiler use the type reference;

Only qualified real parameters can be used for type parameters. Use the WHERE clause to implement constraints.
Class myclass <T1, T2, T3>
Where t2: customer
Where T3: icomparable
{...}
Five types of constraints:
Class Name: only the class of this type or the class inherited from it can be used as a type real parameter;
Class: Any reference type, including classes, arrays, delegates, and interfaces, can be used as real parameters;
Struct: any value type can be used as a type argument;
Interfacename: only this interface or the type that implements this interface can be used as a real parameter;
New (): Any type with a public constructor without any parameters can be used as real parameters. This is called a constructor constraint.

Generic Structure:
Struct pieceofdata <t>
{
Public pieceofdata (T value) {_ DATA = value ;}
Private T _ data;
Public t data
{
Get {return _ data ;}
Set {_ DATA = value ;}
}
}

Generic interface:
Interface imyifc <t>
{
T returnit (T invalue );
}
Class simple <S>: imyifc <S>
{
Public s returnit (s invalue)
{
Return invalue;
}
}
Class simple2: imyifc <int>, imyifc <string>
{
Public int returnit (INT invalue)
{Return invalue ;}
Public String returnit (string invalue)
{Return invalue ;}
}

When you implement a generic interface, there must be no possible combination of type parameters to generate two duplicate interfaces in the type.

Generic delegation:
Delegate R mydelegate <t, r> (T value );
Delegete void mydelegate <t> (T value );
VaR MYDEL = new mydelegate <string> (simple. printstring );

Generic method:
Public void printdata <S, T> (s p) where S: person {...}

Extension methods of generic classes:
Must be declared as static;
Must be a member of a static class;
The first parameter type must have the keyword this, followed by the name of the extended generic class;
Public static void print <t> (this holder <t> H ){...}

The enumerated number and iterator array can provide an object called the enumerated number as needed. The enumerated number can return the elements of the requested array in turn. The enumerated number "knows" the order of items, tracks its position in the sequence, and then returns the current item of the request.

The getenumerator method can be used for enumeration types.

How to Implement enumeration:
Ienumerator/ienumerable interface;
Ienumerator <t>/ienumerable <t> interface;
Do not use the interface form;

The ienumerator Interface contains three methods: Current, movenext, and reset.

The ienumerable interface has only one method: getenumerator, which returns the number of enumerated objects.

Iterator
An iterator block is a block of code with one or more yield statements. The code in the iterator block describes how to enumerate elements.
Yield return executes the next item returned in the sequence;
Yield break specifies that there are no more entries in the sequence;

Public ienumerator <string> blackandwhite ()
{
Yield return "black ";
Yield return "gray ";
Yield return "white ";
}

A new feature that provides the ability to query data.
LINQ (pronounced "Link") indicates language integrated query );
LINQ is an extension of the. NET Framework. It allows us to query data sets in the form of database queries;
C #3.0 contains some extensions from the collection of LINQ to the language, allowing us to query data from databases, program object sets, and XML documents.

Anonymous type:
VaR student = new {lname = "Jones", fname = "Mary", age = 19, Major = "History "};

VaR student = new {age = 19, Major, other. name };
Assignment form; identifier form; member access expression;

Method statement:
Int [] numbers = {2, 5, 28, 31 };
VaR numsmethod = numbers. Where (x => x <20 );

Int [] arr1 = {10, 11, 12, 13 };
VaR query = from item in arr1
Where item <13
Select item;

Int [] numbers = {2, 12, 5, 15 };
Ienumerable <int> lownums = from N in numbers
Where n <10
Select N;

Join clause
VaR query = from S in students
Join C in studentsincourses on S. stid equals C. stid;

From clause
VaR groupA = new [] {3, 4, 5, 6 };
VaR groupB = new [] {6, 7, 8, 9 };
VaR someints = from a in GroupA
From B in GroupB
Where a> 4 & B <= 8
Select New {A, B, sum = a + B };

Let clause: accepts an expression operation and assigns it to an identifier that needs to be used in other operations;
VaR someints = from a in GroupA
From B in GroupB
Let sum = a + B
Where sum = 12
Select New {A, B, sum };

There can be multiple where clauses;

Orderby clause: accepts an expression and returns results based on the expression. Multiple orderby clause can be separated by commas;
By default, the ascending keywords are ascending and the descending keywords are descending;

Group clause:
VaR query = form student in students
Group student by student. Major;
The key is the key used as the basis for grouping.

Query continuation:
VaR someints = from a in GroupA
From B in GroupB On A equals B
Into groupaandb
From C in groupaandb
Select C;

XML class
The most important classes are: xelement, xattribute, and xdocument.

Xdocument employees1 =
New xdocument (
New xelement ("employees ",
New xelement ("name", "Bob Smith "),
New xelement ("name", "Sally Jones ")
)
);
Employees1.save ("employeesfile. xml ");
Xdocument employees2 = xdocument. Load ("employeesfile. xml ");
Console. writeline (employees2 );

Employeesfile. XML content:
<? XML version = "1.0" encoding = "UTF-8"?>
<Employees>
<Name> bob smith </Name>
<Name> Sally Jones </Name>
</Employees>

Method for querying XML:
Nodes
Elements
Element
Descendants
Descendantsandself
Ancestors
Ancestorsandself
Parent

Add/delete nodes and operate XML: add (), addfirst, addbeforeself, addafterself, remove, removenodes

Use XML attributes: the attribute provides additional information about the xelement node, which is placed in the start tag of the XML element.
New xattribute ("color", "Red ");
<Root color = "red">
</Root>

Other types of nodes: xcomment, xdeclaration, and xprocessinginstruction

Use the LINQ to XML to query:
Xdocument XD = xdocument. Load ("simplesample. xml ");
Xelement RT = XD. element ("myelements ");
VaR XYZ = from E in rt. Elements ()
Where E. Name. tostring (). Length = 5
Select E;

Asynchronous programming introduction when we start a program, the system creates a new process in the memory. A process is a group of resources that constitute a running program. These resources include virtual address space, file handle, and the carrier of other things required for program startup.

If the delegate object has only one method in the call list (later called the reference method), it can execute this method asynchronously. The delegate class has two methods: begininvoke and endinvoke. They are used to do this.

The source code of the preprocessing command specifies the program definition. The Preprocessing instruction instructs the compiler how to process the source code.

# Define identifier
# UNDEF identifier
# If expression
# Elif expression
# Else
# Endif
# Region name
# Endregion name
# Warning message
# Error message
# Line indicator
# Pragma text

Example:

# Define debug

...

# If debug
// The code here will be executed
# Else
// Not executed here
# Endif

Reflection and feature-related programs and their types of data are called metadata, which are stored in the program set;
When the program is running, you can view other Assembly or its own metadata. The behavior of a running program to view its own metadata or the metadata of other programs is called reflection.

Type class members: name, namespace, getfields, getproperties, getmethods
Get type object:
Type T = myinstance. GetType ();
Type T = typeof (derivedclass );

A feature is a language structure that allows us to add metadata to the assembly of a program.
The purpose of this feature is to tell the compiler to embed a set of metadata in the program structure into the assembly.
[Serializable]
Public class myclass
{...}

[Myattribute ("simple class", "version 3.57")]
Public class myotherclass
{...}

Predefined features: clscompliant serializable nonserialized obsolete dllimport webmethod attributeusage

Global features: Use assembly and module to set features at the assembly or module level using explicit targets.
Features at the program level must be placed out of any namespace and usually in the assemblyinfo. CS file;
Assemblyinfo. CS files usually contain metadata about the company, product, and copyright information.

Custom features
Public sealed class myattributeattribute: system. Attribute
{...}
Each feature must have at least one common constructor.

Use the isdefined method of type to check whether a feature is applied to a class.
Use the getcustomattributes method to return an array of features applied to the structure.

Other topics: string and stringbuilder
Format the numeric string:
Console. writeline ("the value: {0: c}.", 500); // format the currency
Console. writeline ("the value: {500}.",); // right-aligned in a 10-character field
Standard number formatting specifier;
Parses the string into a numeric value: Double D = double. parse ("25.873"); the other method is tryparse. If the parsing fails, false is returned.

Null type: Create a value type variable and mark it as valid or invalid.
Int? Mynint = 28;
If (mynint! = NULL ){...}
An empty type is implemented by A. Net type called system. nullable <t>.

Main Method
Static void main {...}
Static void main (string [] ARGs ){...}
Static int main (){...}
Static int main (string [] ARGs) {...} // success returns 0
Can be declared as public or private

/// Indicates the document comment

Nested type
Class myclass
{
Classmycounter
{...}
...
}


Document Information

  • Copyright statement: Free Reprint-non commercial-Non derivative-keep the signature | Creative Commons BY-NC-ND 3.0
  • Http://blog.csdn.net/cdztop/article/details/38644345
  • Last modification time: August 17, 2014


Related Article

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.