C#3.0基本特性_第1页
C#3.0基本特性_第2页
C#3.0基本特性_第3页
C#3.0基本特性_第4页
C#3.0基本特性_第5页
已阅读5页,还剩3页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、自动属性C#属性特性使你能够暴露一个类的一片数据,这些数据与如何设置和接收数据采取一种松耦合的方式。Listing 5-4. Using Automatically Implemented Propertiespublic class Product publicint ProductID get; set; public stringName get; set; publicstring Description get; set; publicdecimal Price get; set; publicstring Category set; get;Using Object and Col

2、lection Initializers对象与集合的初始化器Listing 5-7. Using the Object Initializer Featureclass Program static void Main(stringargs) / create a new Product object ProcessProduct(new Product ProductID = 100, Name = "Kayak", Description = "A boat for oneperson", Price = 275M,Category = "

3、Watersports" ); private static void ProcessProduct(ProductprodParam) /.statements to process product in some way Listing 5-8. Initializing Collections and Arraysusing System.Collections.Generic;class Program staticvoid Main(string args) string stringArray = "apple","orange",

4、 "plum" ; List<int>intList = new List<int> 10, 20, 30, 40 ; Dictionary<string,int> myDict = new Dictionary<string, int> "apple", 10 , "orange", 20 , "plum", 30 ; Using Automatic Type Inference自动类型接口C#的var关键词允许你定义一个局部变量而不明确地指定这个变量的类型,如清单

5、5-23所示。这称为类型接口或隐含分类。Listing 5-23. Using Type Inferencevar myVariable = new Product Name ="Kayak", Category = "Watersports", Price = 275M ;string name = myVariable.Name; / legalint count = myVariable.Count; / compiler errorUsing Anonymous Types匿名类型通过结合对象初始化器和类型接口,我们可以生成一个简单的数据存储对象

6、,而不需要定义相应的类或结构。清单5-24演示了一个例子。Listing 5-24. Creating an Anonymous Typevar myAnonType = new Name ="MVC", Category= "Pattern"Console.WriteLine("Name: 0, Type:1", myAnonType.Name, myAnonType.Category);在这个例子中,myAnonType是一个匿名类型对象。这并不意味着它是动态的,JavaScript变量在这种情况下才是动态类型的。这只表示类型定义

7、由编译器自动生成。强类型仍然是必须的。例如,你只可以获取和设置初始化器中已经定义的那些属性。Listing 5-25. Creating an Array of Anonymously Typed Objectsvar oddsAndEnds = new new Name = "MVC", Category = "Pattern", new Name = "Hat", Category = "Clothing", new Name = "Apple", Category = "Frui

8、t"foreach (var item in oddsAndEnds) Console.WriteLine("Name:0", item.Name);Performing Language Integrated Queries执行集成语言查询利用LINQ,我们可以明显地简化这一查询过程,如清单5-27所示。Listing 5-27. Using LINQto Query Datausing System;using System.Linq;class Program staticvoid Main(string args) Productproducts = ne

9、wProduct Name = "Kayak", Category = "Watersports", Price = 275M, newProduct Name = "Lifejacket", Category = "Watersports",Price = 48.95M, newProduct Name = "Soccer ball", Category = "Soccer", Price =19.50M, newProduct Name = "Corner fl

10、ag", Category = "Soccer", Price =34.95M ; var results = from product in products order by product.Price descending select new product.Name, product.Price ; intcount = 0; /print out the names foreach(var p in results) Console.WriteLine("Item:0, Cost: 1", p.Name, p.Price); if(

11、+count = 3) break; Listing 5-28. Using LINQ Dot Notationusing System;using System.Linq;class Program staticvoid Main(string args) Productproducts = new Product Name = "Kayak",Category = "Watersports", Price = 275M, newProduct Name = "Lifejacket", Category = "Waters

12、ports",Price = 48.95M, newProduct Name = "Soccer ball", Category = "Soccer", Price =19.50M, newProduct Name = "Corner flag", Category = "Soccer", Price =34.95M ; var results = products .OrderByDescending(e=> e.Price) .Take(3) .Select(e => new e.Name

13、, e.Price ); foreach (var p in results) Console.WriteLine("Item:0, Cost: 1", p.Name, p.Price); 我们将是第一次容许这种LINQ查询(以黑体表示)不像一个查询语法所表示的那样好看,但并不是所有LINQ特性都有相应的C#关键词。对一个严格的LINQ程序员来说,我们需要切换到使用扩展方法。清单5-28中的每一个LINQ扩展方法都运用于一个IEnumerable<T>并返回一个IEnumerable<T>,这允许我们把这些方法链接在一起形成复杂的查询。OrderBy

14、Descending方法重组数据源中的条目。这里,lambda表达式返回我们要用来比较的值。Take方法返回结果最前面(这是我们用查询语法不能实现的)的一个指定数目的条目。Select方法允许我们设计结果,指定我们想要的结果。这里,我们设计一个匿名对象,它包含了Name和Price属性。注意,我们甚至不需要指定匿名类型中的属性名。C#已经根据我们在Select方法中拾取的属性推断了这些名字。表5-1描述了最有用的LINQ扩展方法。本书中我们到处都使用LINQ,当你看到一个以前还未遇见的扩展方法时,回过来查看此表可能是很有用的。表5-1所显示的所有LINQ方法都是在IEnumerable<

15、T>上进行操作。Table 5-1. Some UsefulLINQ Extension MethodsExtension Method扩展方法 Description描述 Deferred是否延迟 First Returns the first item from the data source返回数据源的第一个条目 No FirstOrDefault Returns the first item from the data source or the default value if there are no items返回数据源的第一个条目,或者,如果无条目时,返回默认值 No L

16、ast Returns the last item in the data source返回数据源的最后一个条目 No LastOrDefault Returns the last item in the data source or the default value if there are no items返回数据源的最后条目,或无条目时返回默认值 No MaxMin Returns the largest or smallest value specified by a lambda expression返回由lambda表达式表示的最大值或最小值 No OrderByOrderByD

17、escending Sorts the source data based on the value returned by the lambda expression根据lambda表达式基于返回值进行排序 Yes Reverse Reverses the order of the items in the data source保留数据源中的条目顺序 Yes Select Projects a result from a query设计一个查询结果 Yes SelectMany Projects each data item into a sequence of items and the

18、n concatenates all of those resulting sequences into a single sequence把每个数据条目投射到一个条目序列之中,然后把所有这些结果序列连接成一个序列 Yes Single Returns the first item from the data source or throws an exception if there are multiple matches返回数据源的第一个适配卡,或者有多个匹配时弹出一个异常 No SingleOrDefault Returns the first item from the data s

19、ource or the default value if there are no items, or throws an exception if there are multiple matches返回数据源的第一个条目,或都没条目时返回默认值,或者有多个条目时返回一个异常 No SkipSkipWhile Skips over a specified number of elements, or skips while the predicate matches跳过指定数目的元素,或者当谓词匹配时跳过 Yes Sum Totals the values selected by the

20、predicate总和谓词选定的值 No TakeTakeWhile Selects a specified number of elements from the start of the data source or selects items while the predicate matches从数据源的开始处选择指定数目的元素,或当谓词匹配时选择指定数目的条目 Yes ToArrayToDictionaryToList Converts the data source to an array or other collection type把数据源转换成数组或其它集合类型 No Wh

21、ere Filters items from the data source that do not match the predicate过滤掉源数据中与谓词不匹配的条目 Yes Understanding Deferred LINQ Queries延迟LINQ查询要注意到表5-1包含了一列Deferred。一条LINQ查询的扩展方法的执行方式有一个有趣的变异。含有deferred方法的一条查询直到IEnumerable<T>结果中的条目被枚举时才会执行,如清单5-29所示。Listing 5-29. UsingDeferred LINQ Extension Methods in

22、 a Queryusing System;using System.Linq;class Program staticvoid Main(string args) Productproducts = new Product Name = "Kayak",Category = "Watersports", Price = 275M, new Product Name = "Lifejacket", Category = "Watersports",Price = 48.95M, new Product Name =

23、"Soccer ball", Category = "Soccer", Price =19.50M, new Product Name = "Corner flag", Category = "Soccer", Price =34.95M ; varresults = products .OrderByDescending(e => e.Price) .Take(3) .Select(e => new e.Name, e.Price ); products2= new Product Name = &q

24、uot;Stadium", Price = 79500M ; foreach(var p in results) Console.WriteLine("Item:0, Cost: 1", p.Name, p.Price); 在这个例子中,我们生成了一个Product对象数组,然后定义我们在前一段的查询。在查询被定义之后,我们修改了Product数据中的一个对象,然后枚举查询结果,这个例子的输出如下:Item: Stadium, Cost: 79500Item: Kayak, Cost: 275Item: Lifejacket, Cost: 48.95你可以看到,直到结果被枚举时,才会求取这个查询,因此,我们所做的修改 把Stadium引入到Product数组 会反映在输出中。相比之下,用任何无deferred扩展方法都会使LINQ查询立即执行。清单5-30提供了一个演示。Listing 5-30. An Immediately Executed LINQ Queryusing System;using System.Linq;clas

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论