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

C#笔记(二)---类型转换

2008-09-10 13:43 381 查看
在用Convert类进行类型转换时,需要注意一些问题:

using System;

struct phoneBook

{

  public string name;

  public uint age;

  public string phone;

  public struct address

  { 

  public string city;

  public string street;

  public uint no;

  }

}

class Welcome

{

  static void Main()

  {

  try

  {

  phoneBook M_1;

  Console.WriteLine("请输入你的姓名:");

  M_1.name=Console.ReadLine();

  Console.WriteLine("请输入你的年龄:");

  M_1.age=Convert.ToUInt32(Console.ReadLine());

  Console.WriteLine("请输入你的电话:");

  M_1.phone=Console.ReadLine();

  Console.WriteLine("请输入你的住址:");

  phoneBook.address ad;  

  Console.WriteLine("请输入你的城市:"); 

  ad.city=Console.ReadLine();

  /*M_1.address.city=Console.ReadLine();*///通过此种方式无法直接访问结构体address的成员

  Console.WriteLine("请输入你的街道:");

  ad.street=Console.ReadLine();

  Console.WriteLine("请输入你的门牌号:");

  ad.no=Convert.ToUInt32(Console.ReadLine());  

   

  Console.WriteLine("OK now……");

  Console.WriteLine("---------------------------------------------------------------------------------");

  Console.WriteLine("你的信息如下:\n");

  Console.WriteLine(" 姓名: {0}",M_1.name);

  Console.WriteLine(" 年龄: {0}",M_1.age);

  Console.WriteLine(" 电话: {0}",M_1.phone);

  Console.WriteLine(" 住址:");

  }

  catch(FormatException e)

  {

   Console.WriteLine("--------------------------------------------------------------------------------");

  string msg = "错误:\n 源:"+e.Source +" \n消息:"+ e.Message;

  Console.WriteLine(msg);

  }

 } 

}

在上面  

ad.no=Convert.ToUInt32(Console.ReadLine());  

中需要将ReadLine()返回的字符串类型转换成uint类型,当输入的是数字时转换正常;但若输入为空或是其他字符时,就会抛出异常:

未处理System.FormatException

  Message="输入字符串的格式不正确。"

  Source="mscorlib"

  StackTrace:

  在System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)

  在System.Number.ParseUInt32(String value, NumberStyles options, NumberFormatInfo numfmt)

  在Welcome.Main()

Convert.ToUInt32 (String) 函数将数字的指定 String 表示形式转换为等效的 32 位无符号整数,原型如下:

[CLSCompliantAttribute(false)] public static uint ToUInt32 (string value)

等效于 value 的值的 32 位无符号整数。 - 或 - 如果 value 为 空引用(在 Visual Basic 中为 Nothing),则为零。

返回值是对 value 调用 Int32.Parse 方法的结果。

当value 不是由一个可选符号后跟数字序列(0 到 9)组成时抛出FormatException异常。

当value 表示小于 MinValue 或大于 MaxValue 的数字时抛出OverflowException异常。


关于FormatException有如下说明:

当方法调用中参数的格式不符合对应的形参类型的格式时,引发 FormatException。例如,如果某方法指定一个 String 参数,该参数由带有嵌入句点的两位数组成,则向该方法传递仅包含两位数的对应字符串参数将导致引发 FormatException。

FormatException 使用值为 0x80131537 的 HRESULT COR_E_FORMAT。

很显然,在上面的情况中是由于输入的字符不是由0-9组成的数字序列而抛出FormatExceptoin异常了,在这里需要提示用户输入不合法,要重新输入0-9的数字,而不是终止程序。因此应对该异常进行如下处理:

 

 while (true)

  {

  try

  {

  Console.WriteLine("请输入你的年龄:");

  M_1.age = Convert.ToUInt32(Console.ReadLine());

  break;

  }

  catch (FormatException e)

  {

  Console.WriteLine("请输入0-9的数字!");

  }

  }

只有在输入正确的情况下才跳出循环,否则只要发生异常就一直循环提示用户输入。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: