C#速成(之二)

-------------------

数据类型
-------------------

所有C#数据类型都派生自基类Object。这里有两类数据类型:

基本型/内置型 用户自定义型

下面一个C#内置类型列表:

** 类型 **** 字节数 **** 解释 **
byte1无符号字节型
sbyte1有符号字节型
short2有符号短字节型
ushort2无符号短字节型
int4有符号整型
uint4无符号整型
long8有符号长整型
ulong8无符号长整型
float4浮点数
double8双精度数
decimal8固定精度数
stringunicode字串型
charunicode字符型
bool真假布尔型

注意: C#当中的类型范围与C++有所不同;例如,C++的long型是4个字节,而在C#当中是8个字节。同样地,bool型和string型都不同于C++。bool型只接受true和false两种值。不接受任何整数类型。

用户定义类型包括:

> > 类类型(class)
>
> 结构类型(struct)
>
> 接口类型(interface)

数据类型的内存分配形式的不同又把它们分成了两种类型:

> > 值类型(Value Types)
>
> 引用类型(Reference Types)
>
> 值类型:

值类型数据在栈中分配。他们包括:所有基本或内置类型(不包括string类型)、结构类型、枚举类型(enum type)

引用类型:

引用类型在堆中分配,当它们不再被使用时将被垃圾收集。它们使用new运算符来创建,对这些类型而言,不存在C++当中的delete操作符,根本不同于C++会显式使用delete这个运算符去释放创建的这个类型。C#中,通过垃圾收集器,这些类型会自动被收集处理。

引用类型包括:类类型、接口类型、象数组这样的集合类型类型、字串类型、枚举类型

枚举类型与C++当中的概念非常相似。它们都通过一个enum关键字来定义。

** 示例: **

> enum Weekdays > { > Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday > }


类类型与结构类型的比较

除了在内存分配形式上外,类与结构的概念完全与C++相同。类的对象被分配在堆中,并且通过new来创建,结构也是被new创建但却被分配在栈当中。C#当中,结构型适于快速访问和拥有少量成员的数据类型。如果涉及量较多,你应该创建一个类来实现他。

(译者注:这与堆和栈内存分配结构的特点有关。简而言之,栈是一种顺序分配的内存;堆是不一定是连续的内存空间。具体内容需要大家参阅相关资料)

示例:

> struct Date > { > int day; > int month; > int year; > } > > class Date > { > int day; > int month; > int year; > string weekday; > string monthName; > > public int GetDay() > { > return day; > } > > public int GetMonth() > { > return month; > } > > public int GetYear() > { > return year; > } > > public void SetDay(int Day) > { > day = Day ; > } > > public void SetMonth(int Month) > { > month = Month; > } > > public void SetYear(int Year) > { > year = Year; > } > > public bool IsLeapYear() > { > return (year/4 == 0); > } > > public void SetDate (int day, int month, int year) > { > > } > ... > }

-------------------

属性
-------------------

如果你熟悉C++面象对象的方式,你就一定有一个属性的概念。在上面示例当中,以C++的观点来看,Data类的属性就是day、month和year。用C#方式,你可以把它们写成Get和Set方法。C#提供了一个更方便、简单、直接的方式来访问属性。

因此上面的类可以被写成:

> using System; > class Date > { > public int Day{ > get { > return day; > } > > set { > day = value; > } > } > > int day; > > public int Month{ > > get { > return month; > } > > set { > month = value; > } > } > > int month; > > public int Year{ > > get { > return year; > } > > set { > year = value; > } > } > > int year; > > public bool IsLeapYear(int year) > { > return year%4== 0 ? true: false; > } > > public void SetDate (int day, int month, int year) > { > this.day = day; > this.month = month; > this.year = year; > } > > }

你可在这里得到并设置这些属性:

> class User > { > > public static void Main() > { > Date date = new Date(); > date.Day = 27; > date.Month = 6; > date.Year = 2003; > Console.WriteLine("Date: {0}/{1}/{2}", date.Day, > date.Month, > date.Year); > } > }
>

Published At
Categories with Web编程
Tagged with
comments powered by Disqus