您的位置:首页 > 其它

Foreach语句,Throw语句,Try,catch语句的使用,报告编译错误

2013-07-12 13:22 471 查看
1、Foreach语句

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace Foreach语句的使用
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Foreach语句的使用";
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.Clear();

Hashtable cityHash = new Hashtable();
cityHash.Add("010", "北京");
cityHash.Add("020", "上海");
cityHash.Add("030", "天津");

Console.WriteLine("电话区号\t城市");
foreach (string a in cityHash.Keys)
{
Console.WriteLine("{0}\t\t{1}", a, cityHash[a]);
}
Console.WriteLine();
Console.Read();
}
}
}


2、Throw语句

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Throw语句的使用
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Throw语句的使用";
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Clear();

string username = "";
try
{
Console.Write("请输入用户名:");
username = Console.ReadLine();
if (username == "")
throw new ArgumentException("", "用户名不能为空!\n");
}
catch(ArgumentException e)
{
Console.ForegroundColor=ConsoleColor.Red;
Console.WriteLine(e.Message);
}
finally
{
Console.ForegroundColor = ConsoleColor.Cyan;
if (username != "")
{
Console.WriteLine("{0}用户,您好!\n", username);
}
}
}
}
}


3、try,catch语句

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Try_Catch语句的使用
{
class Program
{
static void Main(string[] args)
{
int x, y, z = 0;
Console.Title = "异常处理示例";
try
{
Console.Write("请输入一个整数(被除数):");
x = int.Parse(Console.ReadLine());
Console.Write("请输入另一个整数(除数):");
y = int.Parse(Console.ReadLine());
z = x / y;
}
catch(FormatException e)
{
Console.WriteLine("发生异常:{0}", e.GetType());
Console.WriteLine(e.Message);
Console.WriteLine("应输入一个整数");
}
catch (DivideByZeroException e)
{
Console.WriteLine("发生异常:{0}",e.GetType());
Console.WriteLine(e.Message);
Console.WriteLine("除数不能为0");
}
catch(OverflowException e)
{
Console.WriteLine("发生异常:{0}",e.GetType());
Console.WriteLine(e.Message);
Console.WriteLine("输入的数字超出整数范围");
}
finally
{
Console.WriteLine("商={0}",z);
Console.WriteLine("谢谢使用!\n");
}
}
}
}


4、#deine ERROR\#define WARNING

#define ERROR
#define WARNING
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 报告编译错误
{
class Program
{
static void Main(string[] args)
{
#if(ERROR&&WARNING)
//#error
#warning
#endif
Console.WriteLine("Hello,world!!\n");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: