《C#入门经典(中文第四版)》第1章 - 第5章学习笔记
---------------------------------------------------------------------------------------------------------
A1 ………… 基础
A2 ………… using 关键字
A3 ………… as 关键字
A4 ………… is 关键字
A5 ………… switch 关键字
A6 ………… return 语句关键字
A7 ………… enum 关键字
A8 ………… Enum 类
A9 ………… Struct 类型
G1 ………… 数组
G2 ………… String 类
G3 ………… StringBuilder 类
G4 ………… Convert 类
G5 ………… 可空类型 int? & double? & bool?
G6 ………… 值类型 int & double & bool
G7 ………… 引用类型 class & interface & string
G8 ………… 转义字符
G9 ………… 运算符
U1 ………… var 关键字
U2 ………… delegate 委托
U3 ………… 事件
U4 ………… dynamic 关键字
U1 ………… 转义字符
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A1个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● 基础:
- 代码段:工具》代码段管理器,cw,然后双击Tab,即出现Console.WriteLine。
- 帮助》动态帮助,可以动态的现实帮助信息。
- 隐式转换:小范围到大范围,例如:int到long的转换。
-
显示转换:大范围到小范围,特别强调,例如:long到int的转换,enum等。
- 数据类型的Parse()方法,int i = int.Parse("123"); i就位123了。
- 数据类型的ToString()方法,i.ToString() 直接将数字转成字符串。
- 查看或修改项目的.net framework版本:解决方案资源管理器.项目.右键菜单.属性.Application.Target Framework
※ 当修改版本后,一般不能正常运行,可以根据错误提示来解决,一般是代码中的Version出现问题,手动改下就可以了,另外就是一些类,早起的version可能不具有某些类
- Ctrl + Shift + N Create new project
- Ctrl + Shift + O Open a project
- #region
- #endregion 实现代码的折叠
- @"Path:C:\Desktop" @可以消除转义字符
- 变量在使用前必须初始化
- var1 = ++var2; var1的值是var2+1,var2递增1
- var1 = var2++; var1的值是var2,var2递增1
- 具体的数字,不能作为条件表达式,if(10)不成立~
- 三元运算符:<test> ? <resultTure> : <resultFalse>
- switch语句中的case不能用表示范围的数据,所以还是用if吧!
- 常量声明:const int i = 3;不能分开写!
- 强制类型转换:(int)i;i是双精度,转成int
- 异或:用^表示,两者之中有一个是True:if(i==10 ^ j==10)返回有且只有一个等于10的时候~
- 要想使用一些数学函数,要加上math,例如:math.Abs()绝对值
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A2个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● using 关键字:
1. 定义一个范围,将在此范围之外释放一个或多个对象。
2. using 语法:
using (Font font1 = new Font("Arial", 10.0f))
{
}
通过using可以自动实现Close和Dispose方法!凡是继承自IDisposable的类都可以通过using来释放!
※ 参考:C#中using关键字的3中用法
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A3个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● as 关键字:
1. 用于在兼容的引用类型之间执行转换是。
if (button6.Text == "Pause")
{
foreach (Form frm in frms)
{
(frm as Form1).Pause();
}
button6.Text = "Resume";
}
2. as 运算符类似于强制转换操作;但是,如果转换不可行,as 会返回 null 而不是引发异常。更严格地说,这种形式的表达式
expression as type
等效于
expression is type ? (type)expression : (type)null
只是 expression 只被计算一次。
注意,as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用 cast 表达式来执行。
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A4个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● is 关键字:
1. 检查对象是否与给定类型兼容。例如,可以确定对象是否与 string 类型兼容,如下所示:
if (obj is string)
{
}
2. 如果所提供的表达式非空,并且所提供的对象可以强制转换为所提供的类型而不会导致引发异常,则 is 表达式的计算结果将是 true。
3. 请注意,is 运算符只考虑引用转换、装箱转换和取消装箱转换。不考虑其他转换,如用户定义的转换。
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A5个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● switch 关键字:
1. switch 语句是一个控制语句,选择“开关部分” 从候选列表中执行。
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}
break:控制传递给终止语句后面的语句(如果有的话)。
continue:continue 语句将控制权传递给它所在的封闭迭代语句的下一次迭代。(在return链接中)
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A6个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● return 语句关键字:
1.return 语句。
2. 立即结束方法并返回void类型,可以直接跳出 if 语句。
1 public void CalcDiv(int x, int y,ref int result)
2 {
3 if (x <= 0) return;//立即返回操作,下面不再执行
4 result = x / y;
5 }
参考:http://www.cnblogs.com/NatureSex/archive/2011/12/13/2285549.html
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A7个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● enum 关键字:
1. enum关键字定义了字符串和数字,默认情况,从0开始,然后逐渐递增1~默认显示字符串,强制类型转换,显示数字
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
int x = (int)Days.Sun;
enum Days
{
Sat,Sun,Mon,Tue,Wed,Thu,Fri
}
private void Form1_Load(object sender, EventArgs e)
{
TextBox tb = new TextBox();
Controls.Add(tb);
tb.Text = ((int)Days.Fri).ToString();
TextBox tb2 = new TextBox();
Controls.Add(tb2);
tb2.Text = ((Days)2).ToString();
}
// tb:6
// tb2:Mon
}
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A8个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● Enum 类:
1. 遍历enum中成员的方法:(Enum.GetNames、Enum.GetValues)
-
View Code - 遍历enum中成员的四种方法!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch05Ex05
{
class Program
{
enum rainbow
{
red,
orange,
yellow,
green,
cyan,
blue,
violet,
black,
white
}
staticvoid Main(string[] args)
{
for (int i = 0; i < Enum.GetValues(typeof(rainbow)).Length; i++)
{
Console.WriteLine((rainbow)i);
}
Console.WriteLine();
for(int j = 0;j < Enum.GetNames(typeof(rainbow)).GetLength(0);j++)
{
Console.WriteLine((rainbow)j);
}
Console.WriteLine();
foreach (int k in Enum.GetValues(typeof(rainbow)))
{
Console.WriteLine((rainbow)k);
}
Console.WriteLine();
foreach (string h in Enum.GetNames(typeof(rainbow)))
{
Console.WriteLine(h);
}
}
//Output:
//red
//orange
//yellow
//green
//cyan
//blue
//violet
//black
//white
//red
//orange
//yellow
//green
//cyan
//blue
//violet
//black
//white
//red
//orange
//yellow
//green
//cyan
//blue
//violet
//black
//white
//red
//orange
//yellow
//green
//cyan
//blue
//violet
//black
//white
//请按任意键继续. . .
}
} - typeof(类型)得到System.Type
- 实例.GetType()得到System.Type(可以先实例化个enum,然后通过gettype获取类型也可!)
- sizeof(类型)得到值类型的字节大小
- sizeof:http://msdn.microsoft.com/zh-cn/library/eahchzkf%28v=VS.80%29.aspx
2. 通过enum强制类型转换,可以将数字转换为对应的字符串
-
View Code - enum举例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch05Ex02
{
class Program
{
enum Week : byte
{
Sun, Mon, Tue, Wed, Thu, Fri, Sat
}
staticvoid Main(string[] args)
{
Week w = Week.Fri;
string a;
a = Convert.ToString(w);
int i = 1;
for (i = 0; i < 7; i++)
{
Console.WriteLine((Week)i);
}
Console.ReadKey();
}
/* Output:
Sun
Mon
Tue
Wed
Thu
Fri
Sat
*/
}
}
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A9个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● Struct 类型:
1. struct 类型是一种值类型,通常用来封装小型相关变量组,例如,矩形的坐标或库存商品的特征。
public struct Book
{
public decimal price;
public string title;
public string author;
}
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第G1个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● 数组:
1. 数组:<baseType>[ ] <name>; 数组必须在访问前初始化~获取数组大小用name.Length
- int[] myIntArray = {5, 9, 10, 2, 99}; int[] myIntArray = new int[5]; (初始化都为0) int[]myIntArray = new int[] {5, 9, 10, 2, 99};
- foreach (<baseType> <name> in <array>) 前面的<baseType>很重要!
2. 多维数组:可以用foreach,返回所有,用array.Length返回所有数据个数,其他与一维数组相似!
class TestArraysClass { static void Main() { // Declare a single-dimensional array int[] array1 = new int[5]; // Declare and set array element values int[] array2 = new int[] { 1, 3, 5, 7, 9 }; // Alternative syntax int[] array3 = { 1, 2, 3, 4, 5, 6 }; // Declare a two dimensional array int[,] multiDimensionalArray1 = new int[2, 3]; // Declare and set array element values int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } }; // Declare a jagged array int[][] jaggedArray = new int[6][]; // Set the values of the first array in the jagged array structure jaggedArray[0] = new int[4] { 1, 2, 3, 4 }; } }
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第G2个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● String 类:
1. 处理字符串。
2. String 属性:
- Chars:获取当前String对象中位于指定位置的Char对象。
- Length:获取当前String对象中的字符数。
3. String 字段:
- Empty: 此字段为只读。
4. String 方法:
- Split:用来将字符串按照某些分界点转换成数组~
tab键的分割用:'\t' 。表示一个 char 类型的字符。
回车键的分割用:'\n' 。
参考:http://www.aq82.com/blog/post/Csharphuanhang.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch05Ex04
{
class Program
{
staticvoid Main(string[] args)
{
string myWords = "What is your name?";
string[] mySplits = myWords.Split(newchar[]{'','?'});
//Split的分段标准,用一个char数组来表示,若是只有一个' ',则可以直接写成
//string[] mySplits = myWords.Split(' ');
foreach (string mySplit in mySplits)
{
Console.WriteLine(mySplit);
}
Console.ReadKey();
}
/*Output
What
is
your
name
*/
}
}
- EndWith:返回布尔值。
- ToLower:转换为小写。
- ToUpper:转换为大写。
- ToCharArray:可以将字符串转成char数组。
string可以直接用自己的数组,遍历每一个字符:string a = "Hello"; a[0],a[1],a[2]...可以直接用!View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch05Ex04
{
class Program
{
staticvoid Main(string[] args)
{
string myString = "A string";
char[] myChars = myString.ToCharArray();
for (int i = 0; i < myChars.Length; i++)
{
Console.WriteLine(myChars[i]);
}
Console.ReadKey();
}
/*Output
A
s
t
r
i
n
g
*/ - Trim:去除左右空格。
- Trim(new char[]{' ','e','m'}):去除左右的空格、e、m。
- PadLeft(10):10个字符,左边用空格补充。
- PadLeft(10,'-'):10个字符,左边用‘-’补充。
- PadRight:
- Replace(char o, char n):后面的字符替换前面的字符,也可以是string类型的。
- IndexOf(Char):报告指定 Unicode 字符在此字符串中的第一个匹配项的索引。
- IndexOf(Char, Int32): 该搜索从指定字符位置开始。
- IndexOf(String):报告指定字符串在此实例中的第一个匹配项的索引。
- IndexOf(String, Int32): 该搜索从指定字符位置开始。
- LastIndexOf:报告指定字符串在此实例中的最后一个匹配项的索引位置。(也有如上的重载)
※ 指的是最后一个字符的索引位置,依然是从前面数,不是从后面。 - IndexOfAny(Char()):报告指定 Unicode 字符数组中的任意字符在此实例中第一个匹配项的索引。
- SubString(2):从索引2到后面的字符串。
- SubString(2, 5):从索引2,长度为5的字符串。
- Insert(2, "Alex"):在索引2的地方插入。
- Join("=",arr):用“=”将arr数组中的成员连接起来。
- CopyTo方法:
- sourceString.CopyTo(sourceIndex, destination, destinationIndex, count)
- sourceIndex:要复制的此实例(source)中第一个字符的索引。(Int32)
- destination:此实例中的字符所要复制到的字符数组。(Char[])
- destinationIndex:destination中的索引,在此处开始复制操作。(Int32)
- count:此实例(source)中要复制到destination的字符数。(Int32)
-
View Code - CopyTo举例
using System;
publicclass CopyToTest
{
publicstaticvoid Main()
{
// Embed an array of characters in a string
string strSource = "changed";
char[] destination = { 'T', 'h', 'e', '', 'i', 'n', 'i', 't', 'i', 'a', 'l', '',
'a', 'r', 'r', 'a', 'y' };
// Print the char array
Console.WriteLine(destination);
strSource.CopyTo(0, destination, 4, strSource.Length-0);
Console.WriteLine(destination);
string d = "The initial array";
char[] ds = d.ToCharArray();
strSource.CopyTo(0, ds, 4, strSource.Length - 1);
Console.WriteLine(ds);
//The initial array
//The changed array
//The changel array
//请按任意键继续. .
}
}
- Equals:判断是否相同。
- StringComparison 枚举
- 常用String.Equals(String, String, StringComparison.OrdinalIgnoreCase);忽略大小写比较
- Format方法及WriteLine嵌入格式:
-
View Code - Format方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch05Ex05
{
class Program
{
staticvoid Main(string[] args)
{
short[] values = { Int16.MinValue, -27, 0, 1042, Int16.MaxValue };
Console.WriteLine("{0,10} {1,10}\n", "Decimal", "Hex");
foreach (short value in values)
{
string formatString = String.Format("{0,10:G}: {0,10:X}", value);
Console.WriteLine(formatString);
}
}
// The example displays the following output:
// Decimal Hex
//
// -32768: 8000
// -27: FFE5
// 0: 0
// 1042: 412
// 32767: 7FFF
}
} - 通过int16.MinValue、int16.MaxValue、long.MinValue、long.MaxValue可以直接取这些类型的上下限~
- short和int16的范围相同
-
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第G3个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● StringBuilder 类:
1. 表示可变字符字符串。
2. StringBuilder 方法:
- Append:在此实例的末尾追加指定对象的字符串表示形式。
- AppendFormat:按照格式追加。
- AppendLine:一行一行地增加。
- Insert:在指定索引处插入。
3. StringBuilder 属性:
- Capacity:容量。
- Length:长度。
StringBuilder sb = new StringBuilder();
foreach (Control ctr in Controls)
{
sb.AppendLine(ctr.GetType().ToString() + "----" + ctr.Name);
}
MessageBox.Show(sb.ToString());
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第G4个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● Convert 类:
1. 将一个基本数据类型转换为另一个基本数据类型。
2. Convert 方法:
- ToString(Int16, Int32):第二个参数必须为2、8、10、16,将第一个参数转换为相应的二进制、八进制、十进制、十六进制。
int[] bases = {2,8,10,16};
foreach(int i in bases)
Console.WriteLine("{0}进制\r\n{1,10}",i,Convert.ToString(20,i));
运行效果:
2进制
10100
8进制
24
10进制
20
16进制
14 - ToDateTime:将指定的值转换为 DateTime。
DateTime dtSet = Convert.ToDateTime("10:24:58"); //默认加上当前日期
DateTime dt = Convert.ToDateTime("2012/2/28 10:24:58");
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第G5个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● 可空类型 int? & double? & bool?:
1. 可空类型可以表示基础类型的所有值,另外还可以表示 null 值。可空类型可通过下面两种方式中的一种声明:
System.Nullable<T> variable
- 或 -
T? variable
T 是可空类型的基础类型。T 可以是包括 struct 在内的任何值类型;但不能是引用类型。
int? i = 10;
double? d1 = 3.14;
bool? flag = null;
char? letter = 'a';
int?[] arr = new int?[10];
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第G6个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● 值类型 int & double & bool:
1. 值类型主要由两类组成: 结构和枚举。
- bool:
- byte:
- char:
- decimal:
- double:
- enum:
- float:
- int:
- long:
- sbyte
- short
- struct:
- uint:
- ulong:
- ushort:
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第G7个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● 引用类型 class & interface & string:
1. 引用类型的变量又称为对象,可存储对实际数据的引用。
- class:
- delegate:
- interface:
- object:
- string:
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第G8个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● 转义字符:
1. 用反斜杠(\)加上一些字母实现不同的含义!
2. .NET Framework 中的转义字符:
- \b: \u0008 匹配。【Backspace键】
- \t:\u0009 匹配。【Tab键】
- \r:\u000D 匹配。【Enter键】
- \v:\u000B 匹配。(不知道咋用)
- \f:\u000C 匹配。
- \n:\u000A 匹配。
- \{:大括号左。
- \}:大括号右。
- \\: 反斜杠。
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第G9个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● 运算符:
1. C# 提供大量运算符,这些运算符是指定在表达式中执行哪些操作的符号。
2. C# 的运算符如下:
- +:
- -:
- *:
- /:
- % :
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第U1个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● var 关键字:
1. 必须在定义时初始化。
2. 一但初始化完成,就不能再给变量赋与初始化值类型不同的值了。
3. var要求是局部变量。
4. 使用var定义变量和object不同,它在效率上和使用强类型方式定义变量完全一样。
参考:http://topic.csdn.net/u/20110920/19/a5dfeced-a879-4acf-8f8c-2566c22881e7.html
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第U2个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● delegate 委托:
1.有一个返回值和任意数目任意类型的参数:
public delegate void TestDelegate(string message);
public delegate int TestDelegate(MyType m, long num);
2. 将方法作为方法的函数!只定义委托,不用写具体的实现内容,调用的时候,参数为函数名,此函数的特点是与委托有一样的参数,然后不同的函数名称实现不同的函数,若是有返回值,可以获取此值,但是在获取此值的时候要带上相应的参数,不是具体的参数,定义的那种即可!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch06Ex05
{
class Program
{
delegate double ProcessDelegate(double param1, double param2);
static double Multiply(double param1, double param2)
{
return param1 * param2;
}
static double Divide(double param1, double param2)
{
return param1 / param2;
}
static double Plus(double param1,double param2)
{
return param1 + param2;
}
static double Minus(double param1, double param2)
{
return param1 - param2;
}
static void Main(string[] args)
{
ProcessDelegate process;
Console.WriteLine("Enter 2 numbers separated with a comma:");
string input = Console.ReadLine();
int commaPos = input.IndexOf(',');
double param1 = Convert.ToDouble(input.Substring(0, commaPos));
double param2 = Convert.ToDouble(input.Substring(commaPos + 1,
input.Length - commaPos - 1));
Console.WriteLine("Enter M to multiply or D to divide:");
input = Console.ReadLine();
if (input == "M")
process = new ProcessDelegate(Multiply);
else
process = new ProcessDelegate(Divide);
Console.WriteLine("Result: {0}", process(param1, param2));
Console.WriteLine("Enter 2 numbers separated with a comma:");
string input2 = Console.ReadLine();
int commaPos2 = input2.IndexOf(',');
double param11 = Convert.ToDouble(input2.Substring(0, commaPos2));
double param22 = Convert.ToDouble(input2.Substring(commaPos2 + 1));
Console.WriteLine("Enter P to Plus or M to Minus:");
input2 = Console.ReadLine();
if (input2 == "P")
{
process = new ProcessDelegate(Plus);
}
else
{
process = new ProcessDelegate(Minus);
}
Console.WriteLine(process(param11,param22));
Console.ReadKey();
}
}
}
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第U3个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● 事件:
发送(或引发)事件的类称为“发行者”,接收(或处理)事件的类称为“订户”。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
namespace Ch13Ex01
{
class Program
{
static int counter = 0;
static string displayString =
"This string will appear one letter at a time. ";
static void Main(string[] args)
{
Timer myTimer = new Timer(100); //定义时间间隔为100毫秒的Timer!
myTimer.Elapsed += new ElapsedEventHandler(WriteChar);
myTimer.Start();
Console.ReadKey();
}
static void WriteChar(object source, ElapsedEventArgs e)
{
Console.Write(displayString[counter++ % displayString.Length]); //输出一个字符,循环输出
}
}
}
---------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第U4个 ╠══════════════════════════════════════════════════╣
╚════════╝
●·● dynamic 关键字:
dynamic 类型简化了对 COM API(例如 Office Automation API)、动态 API(例如 IronPython 库)和 HTML 文档对象模型 (DOM) 的访问。
dynamic 只在编译时存在,在运行时则不存在。
“对象”。
class Program { static void Main(string[] args) { dynamic dyn = 1; object obj = 1; // Rest the mouse pointer over dyn and obj to see their // types at compile time. System.Console.WriteLine(dyn.GetType()); System.Console.WriteLine(obj.GetType()); } }
将生成以下输出:
System.Int32
System.Int32