一、显示类型转换:
Dictionary<string,object> dict = new Dictionary<string,object>(); dict.Add("Id", "111"); dict.Add("Name", "NAMSDJFIDSJF"); dict.Add("Genger", true); try { var person = (Person)(object)dict; } catch (Exception ex) { Console.WriteLine(ex.Message); }
输出结果:
二、as转换:
Dictionary<string,object> dict = new Dictionary<string,object>(); dict.Add("Id", "111"); dict.Add("Name", "NAMSDJFIDSJF"); dict.Add("Genger", true); try { var person = (object)dict as Person; Console.WriteLine(person); } catch (Exception ex) { Console.WriteLine(ex.Message); }
输出结果:
三、结论
- 显示类型转换失败是直接抛出异常;
- as转换转换失败是返回null.
标签:类型转换,显示,Console,Dictionary,区别,Add,dict,ex From: https://www.cnblogs.com/lixiang1998/p/17840722.html