数据类型转换
隐式
- A的取值范围在B的取值范围内
static void Main(string[] args)
{
ushort ushVar;
char charVar = 'a';
ushVar = charVar;
Console.WriteLine("char var = {0}", charVar );
Console.WriteLine("ushVar var = {0}", ushVar );
Console.ReadKey();
}
// 结果:
// charVar = a
// ushVar = 97
显式
- Convert
- 强制类型转换
- var = (type)var2;
- 强制类型转换的时候要注意,是否会有溢出的可能,下记代买中,destionationVar 就已经溢出了。如果需要编译器注意到这个地方。可以用checked()和unchecked()。
static void Main(string[] args)
{
byte destionationVar;
short sourceVar = 281;
destionationVar = (byte)sourceVar;
Console.WriteLine("sourceVar = {0}", sourceVar);
Console.WriteLine("destionationVar = {0}", destionationVar);
Console.ReadKey();
}
// 结果
// sourceVar = 281
// destionationVar = 25
枚举
- 定义枚举
- 关键字 enum:enum < typeName>
enum < typeName> {
< value1>,
< value2>,
< value2>,
….
< valueN>
} - 声明变量:
< typeName> < varname>;
- 赋值:
< varName> = < typeName>.< value>;
- 枚举用来存储基本类型:byte、sbyte、short、ushort、int、uint、long和ulong。
- 关键字 enum:enum < typeName>
enum orientation : byte {
north = 1,
south = 2,
west = 3,
east = 4
}
struct route {
public orientation direction;
public double distance;
}
class Program
{
static void Main(string[] args)
{
route myRoute;
int myDirection = -1;
double myDistance;
Console.WriteLine("1) North\n 2) South\n 3) East\n 4) West");
do
{
Console.WriteLine("Select a direction:");
myDirection = Convert.ToInt32(Console.ReadLine());
} while ((myDirection < 1) || (myDirection > 4));
Console.WriteLine("Input a distance:");
myDistance = Convert.ToDouble(Console.ReadLine());
myRoute.direction = (orientation)myDirection;
myRoute.distance = myDistance;
Console.WriteLine("myRoute specifiecs a direction of {0} and a" + "distance of {1}", myRoute.direction, myRoute.distance);
Console.ReadKey();
}
}
结构
- 关键字 struct
- 由几个数据组成,数据可以不是同一类型。每个成员的声明如下。
strsuct <typeName> {
<accessibility> <type> <name>;
}
数组
声明数组
<baseType>[] <arrayName>
int[] intArray = {1,2,3,4,5};
<baseType>[] <arrayName> = new <baseType>[arraySize]
int[] intArray = new Int[5] {1,2,3,4,5};
foreach循环
- 定位数组中的每个元素
foreach (<baseType> <name> in <array>) {
// can use <name> for each elemen
}
- 多维数组
- 数组的数组
字符串
- 字符串可以看做char的数组
char[] <name> = <string>.ToCharArray();

本文详细介绍了C#中的变量,包括数据类型的隐式和显式转换,枚举的定义和使用,结构的概念,以及数组和字符串的应用。枚举用于存储基本类型,结构由不同类型的多个数据组成,数组包括一维和多维,字符串则被视为字符数组。
221

被折叠的 条评论
为什么被折叠?



