C # basic knowledge

Source: Internet
Author: User

1. void Main (string [] args)


Using System;
// Program start class
Class NamedWelcome {
// Main begins program execution.
Public static void Main (string [] args ){
// Write to console
Console. WriteLine ("Hello, {0 }! ", Args [0]);
Console. WriteLine ("Welcome to the C # Station Tutorial! ");
}
}

2.Interactive Processing of user input in the console


Using System;
// Program start class
Class NamedWelcome {
// Main begins program execution.
Public static void Main (){
// Write to console/get input
Console. Write ("What is your name? :");
Console. Write ("Hello, {0 }! ", Console. ReadLine ());
Console. WriteLine ("Welcome to the C # Station Tutorial! ");
}
}

Type conversion
(Type) Variable
Convert. toXXX (variable)

Modify

Public can be called by external members.
Internal can be called in the current project
Protected can only be called by class members and subclass of this class. It can only allow the current namespace to access internal access to the current Assembly.
Private can only be called by class members.
3.String and character and array type, structure,Interface,Enumeration
String s = "abc"; // double quotation marks
Char c = 'a'; // single quotes
String [] s = new string [6]; // character array


Class Test
{
Static void Main (){
Int [] a1 = new int [] {1, 2, 3}; // One-dimensional
Int [,] a2 = new int [,] {1, 2, 3}, {4, 5, 6}; // two-dimensional
Int [,] a3 = new int [10, 20, 30]; // 3D
Int [] [] j2 = new int [3] []; // Variable Length
J2 [0] = new int [] {1, 2, 3 };
J2 [1] = new int [] {1, 2, 3, 4, 5, 6 };
J2 [2] = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9 };
}
}

The structure is a value type rather than a reference type, so inheritance is not supported! The structure is stored in the stack or is inline. The structure can improve the storage efficiency. For example, defining a structure with the same information as a class can greatly reduce the storage space.

Struct Point
{
Public int x, y;
Public Point (int x, int y ){
This. x = x;
This. y = y;
}
}

Interface
Interfaces include methods, attributes, indexes, and events.

Interface Example

Enumeration

Definition
Enum Color {
Red,
Blue,
Green
}
Call
Color color1;

4.

Control statement
If else
(Expression )? : Operation 1; Operation 2
Switch (number, character/string, other) case break default
Tag (A1): goto tag (A1 );
While (){}
Do {} while ();
For (;;){}
Foreach (type variable in type set ){}
Break, continue
5.Method

Property modifier return value type method name (parameter) {statement}

Four types of parameters: out (output), ref (reference), params (array), and value (value ).
Void method1 (out string s)
Out: Once the variable is assigned a value, the output parameter is copied to the caller's parameter after the program returns. Therefore, the output parameter must be assigned a value before the method is returned.
Void method1 (ref string s)
Ref (reference): A reference can be passed as a parameter. That is, the reference is copied to the stack. The referenced object is the same as the real parameter referenced by the caller.
Void method1 (params string [] names)
Params (array) must be a one-dimensional or multi-dimensional array

6.Namespace

Using namespace;
Namespace {}
Namespace nesting
Use the full name when calling an object in a namespace without using

7Class
Constructor; destructor; domain; method; attribute; index; proxy ; Events; Nested classes
Class Name {}
Static member of the class

Static void staticPrinter () calls <classname>. <static class member>.
The static member of the call class must pass the class name instead of the Instance name. There is only one copy of the static member of the class.
If you do not need to instantiate an object, you can create static class members.

Destructor ~ Class Name (){}
Inherit class name: parent class name {} the constructor of the parent class is executed before the constructor of the subclass. : Base. The parent class method name () can access members with public or protection permissions of the parent class,ForceAccess the Parent class method (Parent) child). print ();


Using System;
Public class Parent
{
String parentString;
Public Parent ()
{
Console. WriteLine ("Parent Constructor .");
}
Public Parent (string myString)
{
ParentString = myString;
Console. WriteLine (parentString );
}
Public void print ()
{
Console. WriteLine ("I'm a Parent Class .");
}
}
Public class Child: Parent
{
Public Child (): base ("From Derived ")
{
Console. WriteLine ("Child Constructor .");
}
Public void print ()
{
Base. print ();
Console. WriteLine ("I'm a Child Class .");
}
Public static void Main ()
{
Child child = new Child ();
Child. print ();
(Parent) child). print ();
}
}

8.Polymorphism

Virtual Method

Using System;
Public class DrawingObject
{
Public virtual void Draw ()
{
Console. WriteLine ("I'm just a generic drawing object .");
}
}

Virtual modifier, which indicates that the derived class of the base class can overload the method.
Derived classes with overload Methods


Using System;
Public class Line: DrawingObject
{
Public override void Draw ()
{
Console. WriteLine ("I'm a Line .");
}
}
Public class Circle: DrawingObject
{
Public override void Draw ()
{
Console. WriteLine ("I'm a Circle .");
}
}
Public class Square: DrawingObject
{
Public override void Draw ()
{
Console. WriteLine ("I'm a Square .");
}
}

Programs that implement Polymorphism


Using System;
Public class DrawDemo
{
Public static int Main (string [] args)
{
DrawingObject [] dObj = new DrawingObject [4];
DObj [0] = new Line ();
DObj [1] = new Circle ();
DObj [2] = new Square ();
DObj [3] = new DrawingObject ();
Foreach (DrawingObject drawObj in dObj)
{
DrawObj. Draw ();
}
Return 0;
}
}

9.Attribute


Using System;
Public class PropertyHolder
{
Private int someProperty = 0;
Public int SomeProperty
{
Get // write-only if there is no get
{
Return someProperty;
}
Set // read-only if no set exists
{
SomeProperty = value;
}
}
}
Public class PropertyTester
{
Public static int Main (string [] args)
{
PropertyHolder propHold = new PropertyHolder ();
PropHold. SomeProperty = 5;
Console. WriteLine ("Property Value: {0}", propHold. SomeProperty );
Return 0;
}
}

10.Index indicator


Using System;
///
/// A simple indexer example.
///
Class IntIndexer
{
Private string [] myData;
Public IntIndexer (int size)
{
MyData = new string [size];
For (int I = 0; I <size; I ++)
{
MyData [I] = "empty ";
}
}
Public string this [int pos]
{
Get
{
Return myData [pos];
}
Set
{
MyData [pos] = value;
}
}
Static void Main (string [] args)
{
Int size = 10;
IntIndexer myInd = new IntIndexer (size );
MyInd [9] = "Some Value ";
MyInd [3] = "Another Value ";
MyInd [5] = "Any Value ";
Console. WriteLine ("\ nIndexer Output \ n ");
For (int I = 0; I <size; I ++)
{
Console. WriteLine ("myInd [{0}]: {1}", I, myInd [I]);
}
}
}

Heavy-load index indicator


Using System;
///
/// Implements overloaded indexers.
///
Class OvrIndexer
{
Private string [] myData;
Private int arrSize;
Public OvrIndexer (int size)
{
ArrSize = size;
MyData = new string [size];
For (int I = 0; I <size; I ++)
{
MyData [I] = "empty ";
}
}
Public string this [int pos]
{
Get
{
Return myData [pos];
}
Set
{
MyData [pos] = value;
}
}
Public string this [string data]
{
Get
{
Int count = 0;
For (int I = 0; I <arrSize; I ++)
{
If (myData [I] = data)
{
Count ++;
}
}
Return count. ToString ();
}
Set
{
For (int I = 0; I <arrSize; I ++)
{
If (myData [I] = data)
{
MyData [I] = value;
}
}
}
}
Static void Main (string [] args)
{
Int size = 10;
OvrIndexer myInd = new OvrIndexer (size );
MyInd [9] = "Some Value ";
MyInd [3] = "Another Value ";
MyInd [5] = "Any Value ";
MyInd ["empty"] = "no value ";
Console. WriteLine ("\ nIndexer Output \ n ");
For (int I = 0; I <size; I ++)
{
Console. WriteLine ("myInd [{0}]: {1}", I, myInd [I]);
}
Console. WriteLine ("\ nNumber of \" no value \ "entries: {0}", myInd ["no value"]);
}
}

Index indicator with multiple parameters

Public object this [int param1, int paramN]
{
Get
{
// Process and return some class data
}
Set
{
// Process and assign some class data
}
}

11.Exception Handling
Catch exceptions with try-catch
Use try-finally to clear exceptions
Use try-catch-finally to handle all exceptions
Overflow check checked {code segment} non-checkunchecked {}
Catch (System. Exception e)
Catch (OverflowException oe)
You cannot use the ref or out modifier to pass an e or oe object to a method or assign a different value to it. Try can be followed by multiple catch, but pay attention to the exception occurrence and capture order


Exception type description
Exception: base class of all Exception objects
Base classes of all errors generated during SystemException running
IndexOutOfRangeException is triggered when the subscript of an array exceeds the range
NullReferenceException when an empty object is referenced
InvalidOperationException when a call to a method is invalid for the current state of the object, it is triggered by some methods.
ArgumentException base class with all parameter exceptions
ArgumentNullException is triggered by a method when the parameter is null (not allowed ).
ArgumentOutOfRangeException is triggered by a method when the parameter is not within the specified range.
Base class of the InteropException target that is located in or occurs outside the CLR Environment
An exception occurs when ComException contains the HRESULT information of the COM class.
SEHException encapsulates win32 structure Exception Handling Information exceptions

Raise an exception again. cath {... throw;} Or throw e;
Create your own Exception class public class MyImportantException: Exception

----------------
Lock
"Lock" gets a mutually exclusive object lock, which can lock the thread
Lock (object ){...} is to add a mutex lock to an object. Only one thread is allowed to access the statement block in the braces after the block is unlocked until the code is executed, other threads are allowed to execute their statement blocks only after unlocking.
Mutex
Use the Mutex class for synchronization (in/thread)


Define private static Mutex mut = new Mutex ();
Static public Counter_lazy instance ()
{
Mut. WaitOne ();
If (null = uniCounter)
{
UniCounter = new Counter_lazy ();
}
Mut. ReleaseMutex ();
Return uniCounter;
}

Global namespaceGlobal


Class Global
{
Internal static IServer server;
Internal static Hashtable windowList;
Internal static ArrayList contactList;
Internal static string username;
Static Global ()
{
WindowList = new Hashtable ();
ContactList = new ArrayList ();
Username = "";
}
}

Multithreading

Http://www.cnblogs.com/xugang/archive/2008/04/06/1138856.html

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.