最近打算把C#基础重新学一遍,所以发个C#的学习日记,接触C#有近半年了,发现C#在做界面上确实非常强大。以下文章为C#第一章,包括 值与引用,string类型匹配与转义,基本函数,带ref函数,带out函数,运算符,枚举,结构体。参考图书:《C#:开发技术大全》
一.值与引用
值类型存储的是值,而引用类型存储的是对值的引用,相当于C语言的指针将一个值赋值给另外一个变量时,将会新开辟一个内存空间给新变量用来存储值。而对于引用类型,不会新开辟存储空间,只会将地址赋给新的变量。值类型不能包含null,但是引用类型可以。引用类型为Object和String类型,char类型属于String类型内。Object类型是Object的别名,C#中可以将任何类型的值赋给Object类型的变量。
#region valueANDreference
/// <summary>
/// 值与引用
/// </summary>
public void valueANDreference()
{
// new 创建的对象初始值是0.不同类型的默认值不同,但是都有默认值
short shortnew = new short();
char charnew = new char();
byte bytenew = new byte();
short shortS; <span style="font-family: Arial, Helvetica, sans-serif;">//直接定义为未附值,要想使用需要赋值,此处是未赋值,不是NULL</span>
shortS = 1;
Console.WriteLine("short shortnew = new short():{0},
TYPE:{1}", shortnew, shortnew.GetType());
Console.WriteLine("char charnew = new char():{0},
TYPE:{1}", charnew, charnew.GetType()); //char类型默认初始值是null
Console.WriteLine("byte bytenew = new byte():{0},
TYPE:{1}", bytenew, bytenew.GetType());
Console.WriteLine("short shortS=1:{0},
TYPE:{1}, TYPECODE:{2}", shortS, shortS.GetType(), shortS.GetTypeCode());
Console.WriteLine();//空行,等同于ENTER
object objclass = new refClass(); //object 类型,创建类的实例
refClass refclass = (refClass)objclass; //若要将object 类型转化为类实例,需先强制转化
refClass newrefclass = new refClass();
refclass.refint = 1;
Console.WriteLine("类中成员值改变后输出:refint={0}", refclass.refint);
Console.WriteLine("类中成员值未改变后输出:newrefint={0}", newrefclass.refint);
Console.WriteLine();//空行,等同于ENTER
}
#endregion
#region refClass
/// <summary>
/// 用于引用的类
/// 关于类的使用后面再说
/// </summary>
class refClass
{
public int refint = 0; // 为什么此处一定要用public
}
#endregion
二.string 类型匹配与转义
string类型为引用类型(指针类型)
所以在以下程序中我们可以看出,对于值的比较,是TRUE
而对于a和b实例的比较,是FLASE,说明a和b引用的不是同一个string实例。(即a与b指向的不是同一个内存地址)
对于存在'\' 的字符串,如果不是表示转义,需要先对其处理,处理的方法有两种
1.再加一个\
2.在开头前加上@
<span style="white-space:pre"> </span>#region transferredMeaning
///<summary>
///string 类型
/// 值和引用的比较
/// 转义字符串
///</summary>
public void transferredMeaning()
{
string a = "hello";
string b = "h";
b = b + "ello";
string filepathA = "C\\ABC.text";//多加\转义
string filepathB = @"C\ABC.text"; //直接加@转义
Console.WriteLine("a=b直接匹配:{0}", a == b); //输出true
Console.WriteLine("(object)a=(object)b 引用匹配:{0}", (object)a == (object)b); //输出false
Console.WriteLine(); //空行,等同于ENTER
Console.WriteLine("st