文章目录
C# 编程规范
代码书写规则
1、尽量使用接口,然后使用类实现接口,以提高程序的灵活性。
2、尽量不要手工更改计算机生成的代码,若必须更改,一定要改成和计算机生成的代码风格一样。
3、关键的语句(包括声明关键的变量)必须要写注释。
4、建议局部变量在最接近使用它的地方声明。
5、不要使用goto系列语句,除非是用在跳出深层循环时。
6、避免写超过5个参数的方法。如果要传递多个参数,则使用结构。
7、避免书写代码量过大的 try-catch 代码块。
8、避免在同一个文件中放置多个类。
9、生成和构建一个长的字符串时,一定要使用 StringBuilder 类型,而不用 string 类型。
10、switch 语句一定要有 default 语句来处理意外情况。
11、对于 if 语句,应该使用一对 “{}” 把语句块包含起来。
12、尽量不使用 this 关键字引用。
命名规则
1、用帕斯卡( Pascal )规则来命名方法和类型,Pascal 的命名规则是第一 个字母必须大写,并且后面的连结词的第一个字母均为大写。
public class User
{
public void GetInfo()
{
}
}
2、用 驼峰 (Camel) 规则来命名局部变量和方法的参数,Camel 规则是指名称中第一个单词的第一个字母小写,并且后面的连接词的第一个字母均为大写。
string stringUserName;
public void AddUser(strin strUserId, byte[] byPassword)
{
}
3、所有的成员变量前加前缀 “_”。
private string _connectionString;
4、接口的名称加前缀 “I”。
public interface Iconverible
{
byte ToByte();
}
5、方法的命名,一般将 其命名为动宾短语。
public void CreateFile(string filePath)
{
}
public void GetPath(string path)
{
}
6、所有的成员变量声明在类的顶端,用一个换行把它和方法分开。
public class Product
{
private string _producld;
private string _productName;
public void AddProduct(string productld, string productName)
{
}
}
7、用有意义的名字命名空间 namespace,如公司名、产品名。
8、使用某个控件的值时,尽量命名局部变量。
public string GetTitle()
{
string title = lbl_Title.Text.
return title;
}
关键字
int | public | this | finally | boolean | abstract |
continue | float | long | short | throw | return |
break | for | foreach | static | new | interface |
if | goto | default | byte | do | case |
void | try | switch | else | catch | private |
double | protected | while | char | class | using |
using 句法
当对象销毁时自动调用 Dispose 方法。
class MyIDisposable : IDisposable
{
public void Dispose()
{
Console.WriteLine("IDisposable");
}
public static void Test()
{
using (new MyIDisposable())
{
}
}
}
排序
直接插入法
// 直接插入排序法
public static void sort_1()
{
int[] arr = new int[] { 63, 4, 24, 1, 3, 15 };
for (int i = 0; i < arr.Length; ++i)
{
int temp = arr[i];
int j = i;
while((j > 0) && arr[j - 1] > temp)
{
arr[j] = arr[j - 1];
--j;
}
arr[j] = temp;
}
foreach (int i in arr)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
类定义、继承、覆盖、属性定义
// 定义类
class Math_1
{
// 定义属性
private int x;
private int y;
// 定义属性的访问器
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
public int Y
{
get
{
return y;
}
set
{
y = value;
}
}
public int Add()
{
return x + y;
}
}
// 类的继承
class Math_2 : Math_1
{
private int z;
public int Z
{
get
{
return z;
}
set
{
z = value;
}
}
// 类的重写或覆盖
public int Add()
{
return X + Y + z;
}
public static void Test()
{
Math_2 math = new Math_2();
math.X = 1;
math.Y = 2;
math.Z = 3;
Console.WriteLine(math.Add());
Console.ReadLine();
}
}
数据库
ADO.NET
1、连接数据库
关键对象:SqlConnection
关键方法:conn.Open();
string ConStr = "server=serverName;database=" + textBox1.Text.Trim() + ";uid=sa;pwd=123456";
Console.WriteLine(ConStr);
SqlConnection conn = new SqlConnection(ConStr);
conn.Open();
if (conn.State == ConnectionState.Open)
{
string msg= "数据库【" + textBox1.Text.Trim() + "】已经连接并打开";
Console.WriteLine(msg);
}
2、关闭连接
关键方法:conn.Close()、
销毁连接:conn.Dispose();
conn.Close();
if (conn.State == ConnectionState.Closed)
{
str += "数据库已经成功关闭\n";
}
conn.Dispose();
3、查询数据
关键代码:SqlDataReader sdr = cmd.ExecuteReader();
private void button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from t_user;";
cmd.CommandType = CommandType.Text;
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
listView1.Items.Add(sdr[0].ToString());
}
conn.Dispose();
button1.Enabled = false;
}
Lambda 表达式
关键代码:s => (s.IndexOf(“C#”) >= 0)
private static void LambdaTest()
{
string[] strLists = new string[] { "计算机", "C#编程", "C#珍藏版" };
string[] strList = Array.FindAll(strLists, s => (s.IndexOf("C#") >= 0));
foreach(string str in strList)
{
Console.WriteLine(str);
}
Console.ReadKey();
}
窗体事件
占击事件
语法:public event EventHandler Click
this.Click += new System.EventHandler(this.Form1_click);
private void Form1_click(object sender, EventArgs e)
{
MessageBox.Show("hello world!");
}
加载事件
语法:public event EventHandler Load
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
private void Form1_Load(object sender, EventArgs e)
{
}
关闭事件
语法:public event FormClosingEventHandler FormClosing
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("是否关闭窗口", "提示", MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (dr == DialogResult.Yes)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
公共异常类
异常类 | 说明 |
---|---|
ArithmeticException | 在算术运算期间发生的异常 |
ArrayTypeMismatchException | 当存储一一个数组时,如果由于被存储的元素的实际类型与数组的实际类型不兼容而导致存储失败,就会引发此异常 |
DivideByZeroException | 在试图用零除整数值时引发 |
IndexOutOfRangeException | 在试图使用小于零或超出数组界限的下标索引数组时引发 |
InvalidCastException | 当从基类型或接口到派生类型的显示转换在运行时失败,就会引发此异常 |
NullReferenceException | 在需要使用引用对象的场合,如果使用 null 引用,就会引发此异常 |
OutOfMemoryException | 在分配内存的尝试失败时引发 |
OverflowException | 在选中的上下文中所进行的算术运算、类型转换或转换操作导致溢出时引发的异常 |
StackOverflowException | 挂起的方法调用过多而导致执行堆栈溢出时引发的异常 |
TypeInitializationException | 在静态构造函数引发异常并且没有可以捕捉到它的 catch 子句时引发 |
面向对象
抽象类的定义和实现
// 定义抽象类
public abstract class MyClass
{
private string id = "";
private string name = "";
// 定义抽象方法
public abstract void ShowInfo();
public string ID
{
set
{
id = value;
}
get
{
return id;
}
}
public string Name
{
set
{
name = value;
}
get
{
return name;
}
}
}
// 实现抽象类
public class DriveClass : MyClass
{
// 关键字 override 重写
public override void ShowInfo()
{
Console.WriteLine(ID + " " + Name);
Console.ReadKey();
}
public static void Test()
{
DriveClass driveClass = new DriveClass();
MyClass myClass = driveClass;
myClass.ID = "BH0001";
myClass.Name = "TTM";
myClass.ShowInfo();
}
}
接口的定义和实现
interface IMyInterface
{
string ID
{
set;
get;
}
string Name
{
set;
get;
}
void ShowInfo();
}
public class IMyInterfaceImpl : IMyInterface
{
string id = "";
string name = "";
public string ID
{
get
{
return id;
}
set
{
id = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public void ShowInfo()
{
Console.WriteLine("编号\t 姓名");
Console.WriteLine(ID + "\t" + Name);
}
public static void Test()
{
IMyInterfaceImpl myInterfaceImpl = new IMyInterfaceImpl();
IMyInterface myInterface = myInterfaceImpl;
myInterface.ID = "TM";
myInterface.Name = "C#从入门到精通";
myInterface.ShowInfo();
}
}
接口的多重继承
interface IPeople
{
string Name { set; get; }
string Sex { set; get; }
}
interface ITeacher : IPeople
{
void Teach();
}
interface IStudent : IPeople
{
void study();
}
public class Person : IPeople, ITeacher, IStudent
{
string IPeople.Name
{
set { }
get { return ""; }
}
string IPeople.Sex
{
set { }
get { return ""; }
}
public void Teach()
{
}
void IStudent.study()
{
}
}
密封类与密封方法
① 密封类不能作为基类被继承,但它可以继承别的类或接口。
② 在密封类中不能声明受保护成员或虚成员,因为受保护成员只能从派生类进行访问,而虚成员只能在派生类中重写。
③ 由于密封类的不可继承性,因此密封类不能声明为抽象的,即 sealed 修饰符不能与 abstract 修饰符同时使用。
public sealed class MySealedClass
{
public int i = 0;
public void Method()
{
}
}
密封方法
base 关键字。
密封并重写基类中的虚方法 Method() 时, 用到了 base.Method() ;语句, 该语句表示调用基类中的 Method() 方法。base 关键字主要是为派生类调用基类成员提供一种简写的方法。
public class MySealedClass2
{
public int i = 0;
public virtual void Method()
{
}
}
public sealed class MySealedClass3 : MySealedClass2
{
public int i = 0;
public sealed override void Method()
{
}
}
委托和匿名方法
委托的类结构
public class MyDelegateTest
{
public int Add(int x, int y)
{
return x + y;
}
}
public class MyDelegate
{
public delegate int Delegate(int x, int y);
public static void Test()
{
MyDelegateTest test = new MyDelegateTest();
Delegate myDelegate = test.Add;
int intSum = myDelegate(2, 3);
Console.WriteLine("运算结果是 : " + intSum.ToString());
Console.ReadKey();
}
}
多线程
线程的同步
1、使用 lock 关键字
class TestThread
{
static int i = 0;
public static void Test()
{
TestThread t = new TestThread();
Thread thread1 = new Thread(
new System.Threading.ThreadStart(t.LockThread));
thread1.Name = "myThread001";
thread1.Start();
Thread.Sleep(10);
t.LockThread();
}
void LockThread()
{
lock (this)
{
MessageBox.Show(Thread.CurrentThread.Name + " : " + i++);
}
}
}
2、使用 Monitor 同步
void LockThread2()
{
Monitor.Enter(this); // 锁定当前线程
MessageBox.Show(Thread.CurrentThread.Name + " : " + i++);
Monitor.Exit(this); // 释放当前线程
}
3、使用 Mutex 同步
void LockThread3()
{
Mutex mutex = new Mutex(false); // 实例化 Mutex 对象
mutex.WaitOne(); // 阻止当前线程
MessageBox.Show(Thread.CurrentThread.Name + " : " + i++);
mutex.ReleaseMutex(); // 释放 Mutex 对象
}