C#2.0实例程序STEP BY STEP--实例二:数据类型
与其他.NET语言一样,C#支持Common Type Sysem(CTS),其中的数据类型集合不仅包含我们熟悉的基本类型,例如int,char和float等,还包括比较复杂的类型,例如内部的string类型和表示货币值的decimal类型。而且,每种数据类型不仅是一种基本数据类型,还是一个真正的类,其方法可以用与格式化、系列化和类型转换等。
下面看第一个例子:值类型--整数类型
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
class DataTypes
{
public static void Main(string[] args)
{
bool gobool=true;
sbyte sbyteNu; //声明一个sbyte变量,CTS类型为System.sbyte
short shortNu; //声明一个short变量,CTS类型为System.Int16
int intNu; //声明一个int变量,CTS类型为System.Int32
long longNu; //声明一个long变量,CTS类型为System.Int64
byte byteNu; //声明一个byte变量,CTS类型为System.Byte
ushort ushortNu; //声明一个ushort变量,CTS类型为System.Uint16
uint uintNu; //声明一个uint变量,CTS类型为System.Uint32
ulong ulongNu=0; //声明一个ulong变量,CTS类型为System.Uint64
bool testbool=false;
sbyte类型
short类型
Int类型
long类型
byte类型
ushort类型
uint类型
ulong类型
}
}第二个例子:理解值类型和值类型的转换,还有什么是枚举和结构类型。
using System;
class CValue
{
static void Main(string[] args)
{
//值类型定义及初始化
System.Int16 aShort = new System.Int16 ();//System.Int16 等同与 short关键字
byte aByte = new Byte ();
decimal aDecimal = 100.5m;
char aChar = 'y';
Console.WriteLine ("值类型的初始化值:{0} ,{1} ,{2} ,{3}",aShort,aByte,aDecimal,aChar);
//值类型的赋值与操作
float aFloat = 123.123F;
bool aBool = ((aFloat > 121) && (aFloat < 125));
if (aBool) {
int aInteger;
aInteger = (int) aFloat;//显示转换
double aDouble;
aDouble = aFloat; //隐式转换
Console.WriteLine ("类型转换结果:{0} ,{1}",aInteger,aDouble);
}
//枚举类型的使用
long x = (long)Data.Min ;
long y = (long)Data.Max ;
Console.WriteLine ("枚举类型的值:{0} ,{1}",x,y);
//结构的使用
MyPoint aPoint;
aPoint.x = 10;
aPoint.y = 100;
Console.WriteLine ("结构类型的值:{0} ,{1}",aPoint.x ,aPoint.y );
}
//枚举类型的定义
enum Data : long {
Min = 255L, Mid = 1024L, Max = 32768L
};
//结构的定义
public struct MyPoint
{
public int x, y;
public MyPoint( int x, int y)
{
this.x = x;
this.y = y;
}
}
}
class CValue
{
static void Main(string[] args)
{
//值类型定义及初始化
System.Int16 aShort = new System.Int16 ();//System.Int16 等同与 short关键字
byte aByte = new Byte ();
decimal aDecimal = 100.5m;
char aChar = 'y';
Console.WriteLine ("值类型的初始化值:{0} ,{1} ,{2} ,{3}",aShort,aByte,aDecimal,aChar);
//值类型的赋值与操作
float aFloat = 123.123F;
bool aBool = ((aFloat > 121) && (aFloat < 125));
if (aBool) {
int aInteger;
aInteger = (int) aFloat;//显示转换
double aDouble;
aDouble = aFloat; //隐式转换
Console.WriteLine ("类型转换结果:{0} ,{1}",aInteger,aDouble);
}
//枚举类型的使用
long x = (long)Data.Min ;
long y = (long)Data.Max ;
Console.WriteLine ("枚举类型的值:{0} ,{1}",x,y);
//结构的使用
MyPoint aPoint;
aPoint.x = 10;
aPoint.y = 100;
Console.WriteLine ("结构类型的值:{0} ,{1}",aPoint.x ,aPoint.y );
}
//枚举类型的定义
enum Data : long {
Min = 255L, Mid = 1024L, Max = 32768L
};
//结构的定义
public struct MyPoint
{
public int x, y;
public MyPoint( int x, int y)
{
this.x = x;
this.y = y;
}
}
}
Step by step!Create Sunshine!

