学习C#数组
学习C#数组
1、遍历数组和初步接触枚举
using System;
using System.Collections;
namespace system2
{
class Program
{
enum MyColor { 赤, 橙, 黄, 绿, 青, 蓝, 紫 };
enum People { 小明=22,小张=21,小王=16,小吕=23};
static void Main(string[] args)
{
string[] color = Enum.GetNames(typeof(MyColor));
Console.WriteLine("七色光:");
foreach(string c in color)
{
Console.Write("{0}", c);
}
//声明一个枚举类型的数组
People[] person = { People.小明, People.小张, People.小王, People.小吕 };
Console.WriteLine("\n个人信息:");
foreach (People p in person)
{
Console.WriteLine("{0}年龄:{1}", p, p.GetHashCode());
}
Console.ReadLine();
}
}
}
2、添加/删除数组元素
添加/删除数组元素就是在数组中的指定位置对数组元素进行添加或删除,添加数组元素一般是通过使用ArrayList类实现的,可以利用数组的索引号对数组元素进行删除操作,但这种方法不能够真正地实现对数组元素的删除,一般不推荐使用。
using System;
using System.Collections;
namespace system2
{
class Program
{
static void Main(string[] args)
{
string[] furniture = new string[] { "沙发", "床", "桌子", "椅子" };
int length = furniture.Length;//记录删除前的长度
Console.WriteLine("原数组:");
foreach(string f in furniture)
{
Console.Write("{0}\t", f);
}
while (true)
{
//输出提示条件
Console.WriteLine("\n请输入要删除的数组元素索引(索引大于等于0小于{0}):", length);
while (true)
{
int index = Convert.ToInt16(Console.ReadLine());
if (index < 0 || index >= furniture.Length)
{
Console.WriteLine("输入数据不合理,请重新输入:");
continue;
}
else
{
for (int i = index; i < furniture.Length - 1; i = i + 1)
{
furniture[i] = furniture[i + 1];
}
Console.WriteLine("删除成功!");
length = length - 1;
break;
}
}
Console.WriteLine("新数组为:");
foreach (string f in furniture)
{
Console.Write("{0}\t", f);
}
if (length != 0)
{
continue;
}
else
{
break;
}
}
Console.ReadLine();
}
}
}