C#隐式类型
隐式类型
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 隐式类型var { class Program { static void Main(string[] args) { //优点:不需要在左侧也加上Dictionary<string,string>代码得到简化 var dict = new Dictionary<string, string>(); //缺点:从代码上来看不知道具体类型,不容易理解 var a = 2147483649; var b = 928888888888888888; var c = 2147483644; Console.WriteLine("变量a的类型为:{0}", a.GetType()); Console.WriteLine("变量b的类型为:{0}", b.GetType()); Console.WriteLine("变量c的类型为:{0}", c.GetType()); //隐式类型数组 var intarray = new[] { 1, 2, 3, 4 }; var stringarray = new[] { "s", "ad" }; //匿名类型 var person = new { Name = "谢峰", Age = "23" }; Console.WriteLine("{0} 的年龄为:{1}", person.Name, person.Age); //定义匿名类型数组 var personcollection = new[] { new {Name="sam",Age=13}, new {Name="tom",Age=14}, new {Name="jeny",Age=17}, }; var totalAge = 0; foreach (var p in personcollection) { totalAge += p.Age; } Console.WriteLine("所有人的年龄和为:{0}", totalAge); Console.Read(); } } }