欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > C# >内容正文

C#

C#3.0新特性小结(2)

发布时间:2025/4/16 C# 15 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C#3.0新特性小结(2) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

c#3.0中除了自动属性外,还添加:

  • 隐含类型局部变量(Local Variable Type Inference)
  • 匿名类型(Anonymous Types)
  • 对象与集合初始化器(Object and Collection Initializers)

    代码演示实例:

  • //测试数组  
  •         public static void TestArray()  
  •         {  
  •             //测试数组  
  •             var intArray = new[] { 120, 110, 119 };  
  •             var strArray = new[] { "TreeyLee""JFlyZhao""JFlyingchen" };  
  •  
  •             var objArray = new[] {   
  •              //初始化对象  
  •             new {username="马鹏飞",userpass="AdminDoucment"},  
  •             new {username="周静",userpass="周界"}  
  •            };  
  •  
  •             //对单个变量赋值  
  •             var seta =intArray[0];  
  •             var setb = strArray[1];  
  •             var setc = objArray[1].userpass;//可以副单个属性 也可副单个对象objArray[0]  
  •  
  •            //打印当前数据  
  •             Console.WriteLine("seta:" + seta + "\nsetb:" +setb+ "\nsetc:" + setc);  
  •  
  •         }  
  •  
  •     /// <summary>  
  •     /// 综合测试匿名类型  
  •     /// </summary>  
  •   public class TotalTestAnnoy  
  •   {  
  •       //定义属性  
  •       public string username { getset; }  
  •       public string userpass { getset; }  
  •       public int age { getset; }  
  •          
  •       //定义测试方法  
  •       public static void TestMethods()  
  •       {  
  •           //集合初始化器  
  •           List<TotalTestAnnoy> TotalList = new List<TotalTestAnnoy> {   
  •            //不能直接写new {} 集合器中只能装TotalTestAnnoy对象,不能var类型  
  •             new TotalTestAnnoy{username="老顾",userpass="laogu",age=21},  
  •             new TotalTestAnnoy{username="周静",userpass="zhoujing",age=26},  
  •             new TotalTestAnnoy{username="陈凯",userpass="chenkai",age=21}  
  •           };  
  •  
  •           //定义匿名类型  
  •           var GetTotalList = from newtotallist in TotalList  
  •                              where newtotallist.age == 21//吧结果定义成一个新对象 只包含两个属性newname 和newpass  
  •                              select new { newname = newtotallist.username, newpass = newtotallist.userpass };  
  •           //循环打印新对象  
  •           foreach(var getfirst in GetTotalList)  
  •           {  
  •               //打印新实例结果  
  •               Console.WriteLine("定义新实例newname:"+getfirst.newname+"\nnewpass:\n"+getfirst.newpass);  
  •           }  
  •  
  •       }  
  •  
  •         
  •   } 
  •  

    转载于:https://blog.51cto.com/chenkai/765463

    总结

    以上是生活随笔为你收集整理的C#3.0新特性小结(2)的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。