C#使用手册(持续更新)

常用数据类型

获取精确到毫秒的时间
string s= string.Format(“{0:yyyy/MM/dd HH:mm:ss.fff}”,DateTime.Now);

运算符

算数运算符
+

*
/
%
++

关系运算符
==
!=
>
<
>=
<=
逻辑运算符
&&
||

位运算符
&
|
^
~
<<
>>
赋值运算符
=
+=
-=
*=
/=
%=
<<=
>>=
&=
^=
|=
其它运算符
sizeof()
typeof()
&取变量地址
*变量的指针
?:条件表达式
is判断对象是否为某一类型
as强制转换,即使转换失败也不会抛出异常

数据类型转换
隐式转换
系统自动执行,允许范围小的数向范围大的数转换。
int x = 123;
float y = x;
显式转换(强制转换)
decimal x = 123;
float y =(float) x;
特定方法
Parse()方法
ToString()方法
int x = int.Parse(“123”);
string s = x.ToString();
Conver类
int x = Convert.ToInt32(“123”);
string s = Convert.ToString(123);

程序执行计时功能

using System.Diagnostics;

Stopwatch stopwatch = new Stopwatch();
stopwatch.Restart();
Thread.Sleep(1234);
stopwatch.Stop();
this.label1.Text = stopwatch.ElapsedMilliseconds.ToString();

匿名方法与Lambda表达式

namespace ConsoleApp2

{

class Program

{

delegate void DelegateMethod(string str);

static void PrintStr(string str)

{

Console.WriteLine(str);

}

static void Main(string[] args)

{

DelegateMethod dm = PrintStr;

dm(“Hello World!”);

Console.Read();

}

}

}

采用匿名函数的写法

namespace ConsoleApp2

{

class Program

{

delegate void DelegateMethod(string str);

static void Main(string[] args)

{

DelegateMethod dm = delegate (string str) { Console.WriteLine(str); };

dm(“Hello World!”);

Console.Read();

}

}

}

后续开始使用lambda表达式取代了匿名函数,而且应用范围更广。

Lambada表达式

(参数)=>{表达式}

0或多个参数()不能必须保留,一个参数()可以不写;

一条语句{}可以不写,否则必须保留;

namespace ConsoleApp2

{

class Program

{

static void Main(string[] args)

{

Action AM = (str) => { Console.WriteLine(str); };

AM(“Hello World!”);

Func<int, int, double> FM = (x, y) => { return  x + y; };

Console.WriteLine(FM(123,456));

Console.Read();

}

}

}

异步编程的示例

namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

//async/await关键词调用或者调用此方法
private void button1_Click(object sender, EventArgs e)
{
callAddAysnc();
}
private async void callAddAysnc()
{
string r = await addAysnc(123, 456);
MessageBox.Show(r);
}

//方法封装成任务
private Task addAysnc(int a, int b)
{
return Task.Run(() => { return add(a, b); });
}

//耗时方法
private string add(int a, int b)
{
Thread.Sleep(10000);
return (a + b).ToString();
}
}
}