C# 基础知识整理篇

1.  void Main(string[] args)

clip_image001
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. 控制台交互式处理用户输入

clip_image001[1]
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!");
}
}

类型转换
(类型)变量
Convert.toXXX(变量)

修饰

public   可以被外部成员调用
internal   可以在当前项目调用
protected   只能在被类的成员和该类的子类调用 只能让当前命名空间访问 internal 访问仅限于当前程序集。
private   只能在被类的成员调用
3. 字符串与字符及数组类型,结构,接口,枚举
string s = "abc";//双引号
char c= 'a';//单引号
string[] s=new string[6];//字符数组

clip_image001[2]
class Test 

static void Main() { 
int[] a1 = new int[] {1, 2, 3}; //一维
int[,] a2 = new int[,] {{1, 2, 3}, {4, 5, 6}}; //二维
int[,,] a3 = new int[10, 20, 30]; //三维
int[][] j2 = new int[3][]; //变长
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}; 

}

结构是值类型,而不是引用类型,所以不支持继承!结构被存在堆栈中或者是内联。结构在精心下可以提高存储效能。例如,定义一个与类有着相同信息的结构可以大大地减少存储空间

struct Point 

public int x, y; 
public Point(int x, int y) { 
this.x = x; 
this.y = y; 

}

接口
接口包含以下成员:方法、属性、索引和事件

clip_image002接口示例

枚举

定义
enum Color { 
Red, 
Blue, 
Green 

调用
Color color1;

4.

控制语句
if else
(表达式)?  : 操作1 ; 操作2
switch(数字,字符/串,other) case break default
标签(A1):   goto 标签(A1);
while(){}
do{}while();
for(;;){}
foreach( 类型变量 in 类型集 ){}
break , continue
5. 方法

属性 修饰符 返回值类型 方法名(参数) { 语句 }

四种类型的参数:out(输出),ref(引用),params(数组)和value(值)。
void method1(out string s) 
      out(输出): 一旦该变量被赋了值,在程序返回之后,输出参数就被拷贝到调用者的参数中。所以,在方法返回之前,必须给输出参数赋值。
void method1(ref string s) 
      ref (引用) : 即引用可作为参数来传递,即该引用被拷贝到栈中,其引用的对象同调用者的实参所引用的对象是同一个
void method1(params string[] names) 
      params(数组)须是一维或多维的数组

6.名称空间

using 名称空间;
namespace 名称空间 {}
名称空间可嵌套
不使用 using  调用名称空间内对象时要使用全称

7
构造函数;析构函数;域;方法;属性;索引;代理 ;事件;嵌套类
class 类名{}
类的静态成员

static void staticPrinter()  调用 <classname>.<static class member>。
调用类的静态成员必须通过类名而不是实例名。类的静态成员的副本仅有一个。
如果没有必要实例化一个对象,可以创建静态的类成员

析构函数  ~类名(){}
继承 class 类名:父类名{} 父类的构造函数在子类的构造函数之前执行。:base.父类方法名() 可以访问父类的具有公有或者保护权限的成员, 强制访问父类方法((Parent)child).print();

clip_image001[3]
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. 多态性

虚方法

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

virtual修饰符,该修饰符表明:该基类的派生类可以重载该方法
带有重载方法的派生类

clip_image001[4]
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.");
}
}

实现多态性的程序

clip_image001[5]
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. 属性

clip_image001[6]
using System;
public class PropertyHolder
{
private int someProperty = 0;
public int SomeProperty
{
get //没有get 则为只写
{
return someProperty;
}
set //没有set 则为只读
{
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. 索引指示器

clip_image001[7]
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]);
}
}
}

重载的索引指示器

clip_image001[8]
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"]);
}
}

带有多个参数的索引指示器

public object this[int param1, clip_image003, int paramN]
{
get
{
// process and return some class data
}
set
{
// process and assign some class data
}
}

11. 异常处理
用 try-catch 捕获异常
用try-finally 清除异常
用try-catch-finally 处理所有的异常
溢出校验checked{代码段}  非校验unchecked {}
catch(System.Exception e)
catch (OverflowException oe)
不能用ref或out 修饰符传递 e 或 oe 对象给一个方法,也不能赋给它一个不同的值。try 后可跟多个catch 但要注意异常出现与捕捉的顺序

clip_image001[9]
异常类型 描述
Exception 所有异常对象的基类
SystemException 运行时产生的所有错误的基类
IndexOutOfRangeException 当一个数组的下标超出范围时运行时引发
NullReferenceException 当一个空对象被引用时运行时引发
InvalidOperationException 当对方法的调用对对象的当前状态无效时,由某些方法引发
ArgumentException 所有参数异常的基类
ArgumentNullException 在参数为空(不允许)的情况下,由方法引发
ArgumentOutOfRangeException 当参数不在一个给定范围之内时,由方法引发
InteropException 目标在或发生在CLR外面环境中的异常的基类
ComException 包含COM 类的HRESULT信息的异常
SEHException 封装win32 结构异常处理信息的异常

重新引发一个异常  cath{..... throw;}  或 throw e;
创建自己的异常类 public class MyImportantException:Exception

----------------
lock
“lock”获得一个相互排斥的对象锁定,可进行线程的加锁
lock(对象){...}是对一个对象加互斥锁,只允许一个线程访问其后大括号中语句块,直到该语句块的代码执行完才解锁,解锁后才允许其他的线程执行其语句块。
Mutex
使用Mutex类进行同步(进/线程)

clip_image001[10]
定义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

clip_image001[11]
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="";
        }
    }

多线程

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

原文地址:https://www.cnblogs.com/tangge/p/2101536.html