您的位置:首页 > 编程语言 > C#

c#每日小结 <五>

2011-07-18 09:03 381 查看
结构与枚举[/b]
1、 [/b]结构[/b]
(1)结构与类的区别:
1. 结构是值类型,而类属于引用;
2. 结构的实例化可以用new,也可以不用的;
3. 结构的构造函数默认为无参的,当人为的定义了一个有参的构造函数后,实例化的时候仍然可以调用无参的,而且,人为的定义构造函数一定要带参数。
4. 结构不能继承结构或类,所有的结构都是继承自system.valuetype,system.valuetype继承system.object。但是结构可以实现接口;
(2)结构中的字段不能够赋初值。
(3)结构的访问修饰符:public,internal,默认:internal;
成员访问修饰符可以是不private,public,不能为protected
例如:
struct stu
{
static in iu=23;//静态字段可以[/b] ,const同static
public int age;//不能赋初值[/b]
public stu(int age)//必须带参数[/b] [/b]
{
this.age = age;
}
}
static void Main(string[] args)
{
stu s = new stu();//new[/b]生成实例[/b]
s.age = 17;
stu s1;//[/b]直接生成实例[/b][/b]
s1.age = 14;
Console.WriteLine(stu.iu);//[/b]由结构名调用[/b];
Console.WriteLine(s.age+" "+s1.age);


2、 [/b]枚举[/b]
(1)关键字:enum;[/b]
(2)每种枚举类型都可以是除 char以外的任何整形,枚举元素的默认值基础类型是int,默认情况下,第一个枚举数的值为
0;后面元素依次递增1。
当属性有多个枚举值的时候,可以采用位枚举。
[Flags]
enum Wei
{
A = 1,
B = 2,
C = 4,
D = 8
}

static void Main(string[] args)
{
Wei w = Wei.A | Wei.B | Wei.C;
Console.WriteLine(w);
foreach (string str in Enum.GetNames(typeof(ConsoleColor)))//获取枚举类中的元素名称
{
Console.WriteLine(str);
}
Console.WriteLine((Wei)6);

Console.WriteLine(Enum.Format(typeof(Wei),2,"G"));//B Console.WriteLine(Enum.Format(typeof(Wei),2,"X"));//2
Console.WriteLine(Enum.Format(typeof(Wei), 2, "D"));//00000002 Console.WriteLine(Enum.Format(typeof(Wei), 2, "F"));//B
[/b]
二维数组,交错数组的存取,
//[/b]二维数组[/b][/b]
int[,] arr = new int[,] { {1,2,3,4},{5,6,7,8}};
foreach (int i in arr)
{
Console.WriteLine(i);
}
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i,j]+"\t");
}
Console.WriteLine();
}
//[/b]交错数组[/b][/b]
int[][] arr1 = new int[3][];
arr1[0] = new int[] { 1,2,3};
arr1[1] = new int[] { 1, 2 };
arr1[2] = new int[] { 1,2,3,4};
foreach (int[] i in arr1)
{
foreach (int j in i)
{
Console.WriteLine(j);
}
}
//[/b]三维数组[/b][/b]
int[ , ,] arr2 = new int[ ,,] { {{1,2},{3,4}}, {{5,6},{7,8}}, {{9,10},{11,12}}};

foreach(int i in arr2)
{
Console.WriteLine(i);
}

for (int i = 0; i < arr2.GetLength(0);i++ )
{
for (int j = 0; j < arr2.GetLength(1);j++ )
{
for (int k = 0; k < arr2.GetLength(2);k++ )
{
Console.WriteLine(arr2[i,j,k]);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息