当尝试在数组中存储错误类型的元素时,会抛出arraytypemismatchException。
如何处理.NET中的ArrayTyPeMismatchException 示例
using System; using System.Collections.Generic; using System.Linq; using System.Text namespace ArrayTypeMismatch { class Class1 { static void Main(string[] args) { string[] names = { "jack", "tom", "bob" }; object[] objs = (object[])names; try { objs[2] = "lilei"; foreach (object Name in objs) { System.Console.WriteLine(Name); } } catch (System.ArrayTypeMismatchException) { System.Console.WriteLine("Exception Thrown."); } try { Object obj = (Object)13; objs[2] = obj; } catch (System.ArrayTypeMismatchException e) { Console.WriteLine(e.Message); //13不是字符串 System.Console.WriteLine( "类型不正确"); } //将objs设置为对象数组而不是字符串数组。 objs = new Object[3]; try { objs[0] = (Object)"alan"; objs[1] = (Object)8; objs[2] = (Object)12.12; foreach (object element in objs) { System.Console.WriteLine(element); } } catch (System.ArrayTypeMismatchException) { //这次不抛出ArrayTypeMismatchException 异常 System.Console.WriteLine("Exception Thrown."); } Console.ReadLine(); } } }
日期:2020-04-11 22:50:14 来源:oir作者:oir