C#4.0新特性.doc_第1页
C#4.0新特性.doc_第2页
C#4.0新特性.doc_第3页
C#4.0新特性.doc_第4页
C#4.0新特性.doc_第5页
已阅读5页,还剩49页未读 继续免费阅读

下载本文档

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

文档简介

翻译 C# 4.0新特性(白皮书)原文地址:/Project/Download/FileDownload.aspx?ProjectName=csharpfuture&DownloadId=3550(Word格式,需接受许可协议并下载。)原著作者:Mads Torgersen, C# Language PM翻译:Anders Liu摘要:Microsoft Visual C# 3.0作为Visual Studio 2008的一部分发布以来已经快一年了。在VS Managed Languages团队,我们一直努力创建该语言的下一个版本(没什么惊喜,就是C# 4.0),而这个文档是我们现在所看到的、计划中的语言特性的第一个公开描述。Contents目录 Introduction 简介 C# 4.0 Dynamic Lookup 动态查找 The dynamic type dynamic类型 Dynamic operations 动态操作 Runtime lookup 运行时查找 Example 示例 Overload resolution with dynamic arguments 带有动态参数的重载解析 The Dynamic Language Runtime 动态语言运行时 Open issues 已知问题 Named and Optional Arguments 命名参数和可选参数 Optional parameters 可选参数 Named and optional arguments 命名的和可选的实参 Overload resolution 重载解析 Features for COM interop COM互操作特性 Dynamic import 动态引入 Compiling without PIAs 无PIA的编译 Omitting ref 省略ref Open issues 已知问题 Variance 变性 Covariance 协变性 Contravariance 逆变性 Limitations 限制 COM Example COM示例 Relationship with Visual Basic 与Visual Basic的关系 Resources 资源 Introduction简介It is now close to a year since Microsoft Visual C# 3.0 shipped as part of Visual Studio 2008. In the VS Managed Languages team we are hard at work on creating the next version of the language (with the unsurprising working title of C# 4.0), and this document is a first public description of the planned language features as we currently see them.Microsoft Visual C# 3.0作为Visual Studio 2008的一部分发布以来已经快一年了。在VS Managed Languages团队,我们一直努力创建该语言的下一个版本(没什么惊喜,就是C# 4.0),而这个文档是我们现在所看到的、计划中的语言特性的第一个公开描述。Please be advised that all this is in early stages of production and is subject to change. Part of the reason for sharing our plans in public so early is precisely to get the kind of feedback that will cause us to improve the final product before it rolls out.请记住本文内容都是针对产品早期的,而且将来会改变。这么早地共享我们的计划,一部分原因是为了获取某些反馈,这些反馈会让我们在产品最终发布出来之前改进它。Simultaneously with the publication of this whitepaper, a first public CTP (community technology preview) of Visual Studio 2010 is going out as a Virtual PC image for everyone to try. Please use it to play and experiment with the features, and let us know of any thoughts you have. We ask for your understanding and patience working with very early bits, where especially new or newly implemented features do not have the quality or stability of a final product. The aim of the CTP is not to give you a productive work environment but to give you the best possible impression of what we are working on for the next release.与该白皮书一同发布的还有Visual Studio 2010的第一个公开的CTP(社区技术预览),它通过Virtual PC映像发布,任何人都可以试用。请使用这个CTP来把玩和试验这些特性,并让我们知道您的想法。我们希望知道您对这个早期产品的理解和不满,尤其是新添加的实现特性是否不具备最终产品应有的质量和稳定性。这个CTP的目的不是为您提供一个高生产力的工作环境,而是让您对我们正在为下一个发布版做些什么有个印象。The CTP contains a number of walkthroughs, some of which highlight the new language features of C# 4.0. Those are excellent for getting a hands-on guided tour through the details of some common scenarios for the features. You may consider this whitepaper a companion document to these walkthroughs, complementing them with a focus on the overall language features and how they work, as opposed to the specifics of the concrete scenarios.该CTP包含了大量的演练,其中一些着重于C# 4.0的语言新特性。要详细了解这些特性的常用场景,这些演练是绝好的上手教程。您可以认为该白皮书是这些演练的伴随文档,全面地介绍了语言的特性和工作原理,而那些演练则是介绍具体的场景。C# 4.0The major theme for C# 4.0 is dynamic programming. Increasingly, objects are “dynamic” in the sense that their structure and behavior is not captured by a static type, or at least not one that the compiler knows about when compiling your program. Some examples includeC# 4.0的主要主题是动态编程。对象的意义变得越来越“动态”,它们的结构和行为无法通过静态类型来捕获,或者至少编译器在编译程序时无法得知对象的结构和行为。例如 a. objects from dynamic programming languages, such as Python or Ruby b. COM objects accessed through IDispatch c. ordinary .NET types accessed through reflection d. objects with changing structure, such as HTML DOM objects a. 来自动态编程语言如Python或Ruby的对象 b. 通过IDispatch访问的COM对象 c. 通过反射访问的一般.NET类型 d. 结构发生过变化的对象如HTML DOM对象 While C# remains a statically typed language, we aim to vastly improve the interaction with such objects.尽管C#依然是静态类型语言,但我们的目的是改善它与这些对象的交互。A secondary theme is co-evolution with Visual Basic. Going forward we will aim to maintain the individual character of each language, but at the same time important new features should be introduced in both languages at the same time. They should be differentiated more by style and feel than by feature set.另一个次要主题是与Visual Basic协同进步(co-evolution)。将来我们希望仅维护每种语言单独的特征,而重要的新特性会同时引入两种语言。它们的区别仅仅是风格和感觉上的,而不在于特性集方面。The new features in C# 4.0 fall into four groups:C# 4.0中的新特性分为四组Dynamic lookup动态查找Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the C# static type checking and instead gets resolved at runtime. 动态查找允许在编写方法、运算符和索引器调用、属性和字段访问甚至对象调用时,绕过C#静态类型检查,而在运行时进行解析。Named and optional parameters命名参数和可选参数Parameters in C# can now be specified as optional by providing a default value for them in a member declaration. When the member is invoked, optional arguments can be omitted. Furthermore, any argument can be passed by parameter name instead of position.现在C#中的参数可以通过在成员声明中为其提供默认值来指名它是可选的。在调用该成员时,可选参数可以忽略。另外,在传入任何参数时都可以按照参数名而不是位置进行传递。COM specific interop features特定于COM的互操作特性Dynamic lookup as well as named and optional parameters both help making programming against COM less painful than today. On top of that, however, we are adding a number of other small features that further improve the interop experience.动态查找以及命名参数和可选参数都有助于使针对COM的编程不再像今天这样痛苦。在这些特性之上,我们还添加了大量其他小特性,进一步改善了互操作体验。Variance变性It used to be that an IEnumerable wasnt an IEnumerable. Now it is C# embraces type safe “co-and contravariance” and common BCL types are updated to take advantage of that.过去,IEnumerable并不是IEnumerable。现在它是了C#包含了类型安全的“协变性和逆变性(co-and contravariance)”而且通用的BCL也将利用这一特性进行更新。Dynamic Lookup动态查找Dynamic lookup allows you a unified approach to invoking things dynamically. With dynamic lookup, when you have an object in your hand you do not need to worry about whether it comes from COM, IronPython, the HTML DOM or reflection; you just apply operations to it and leave it to the runtime to figure out what exactly those operations mean for that particular object.动态查找可以用统一的方式来动态调用成员。有了动态查找,当你拿到一个对象时,不用管它是来自于COM还是IronPython、HTML DOM或是反射;只需要对其进行操作即可,运行时会帮你指出针对特定的对象,这些操作的具体意义。This affords you enormous flexibility, and can greatly simplify your code, but it does come with a significant drawback: Static typing is not maintained for these operations. A dynamic object is assumed at compile time to support any operation, and only at runtime will you get an error if it wasnt so. Oftentimes this will be no loss, because the object wouldnt have a static type anyway, in other cases it is a tradeoff between brevity and safety. In order to facilitate this tradeoff, it is a design goal of C# to allow you to opt in or opt out of dynamic behavior on every single call.这给你带来了巨大的灵活性,并能极大程度地精简代码,但它伴随着一个巨大的缺点不会为这些操作维护静态类型。在编译时,会假设动态对象支持任何操作,而如果它不支持某个操作,则只有到运行时才能得到错误。有的时候这不会有任何损失,因为对象根本不具有静态类型,而且他情况下必须在简洁和安全之间进行权衡。为了帮助进行权衡,C#的一个设计目标就是允许在每个单独的调用中选择是否使用动态行为。The dynamic typedynamic类型C# 4.0 introduces a new static type called dynamic. When you have an object of type dynamic you can “do things to it” that are resolved only at runtime:C# 4.0引入了一个新的静态类型,称为dynamic。当你拥有了一个dynamic类型的对象后,你“对他做的事情”只会在运行时进行解析view plaincopy to clipboardprint? dynamicd=GetDynamicObject(.); d.M(7);The C# compiler allows you to call a method with any name and any arguments on d because it is of type dynamic. At runtime the actual object that d refers to will be examined to determine what it means to “call M with an int” on it.C#编译器允许你使用任何参数在d上调用一个方法,因为它的类型是dynamic。运行时会检查d的实际类型,并检测在它上面“用一个int调用M”是什么意思。The type dynamic can be thought of as a special version of the type object, which signals that the object can be used dynamically. It is easy to opt in or out of dynamic behavior: any object can be implicitly converted to dynamic, “suspending belief” until runtime. Conversely, there is an “assignment conversion” from dynamic to any other type, which allows implicit conversion in assignment-like constructs:可以认为dynamic类型是object类型的一个特殊版本,指出了对象可以动态地使用。选择是否使用动态行为很简单任何对象都可以隐式转换为dynamic,“挂起信任”直到运行时。反之,从dynamic到任何其他类型都存在“赋值转换”,可以类似于赋值的结构中进行隐式转换view plaincopy to clipboardprint? dynamicd=7;/implicitconversion inti=d;/assignmentconversionDynamic operations动态操作Not only method calls, but also field and property accesses, indexer and operator calls and even delegate invocations can be dispatched dynamically:不仅是方法调用,字段和属性访问、索引器和运算符调用甚至委托调用都可以动态地分派view plaincopy to clipboardprint? dynamicd=GetDynamicObject(); d.M(7);/callingmethods d.f=d.P;/gettingandsettingsfieldsandproperties d“one”=d“two”;/gettingandsettingthorughindexers inti=d+3;/callingoperators strings=d(5,7);/invokingasadelegateThe role of the C# compiler here is simply to package up the necessary information about “what is being done to d”, so that the runtime can pick it up and determine what the exact meaning of it is given an actual object d. Think of it as deferring part of the compilers job to runtime.C#编译器在这里的角色就是打包有关“在d上做什么”的必要信息,使得运行时可以获取这些信息并检测对于实际对象d这些操作的确切含义。可以认为这是将编译器的部分工作延迟到了运行时。The result of any dynamic operation is itself of type dynamic.任何动态操作的结果本身也是dynamic类型的。Runtime lookup运行时查找At runtime a dynamic operation is dispatched according to the nature of its target object d:在运行时,动态操作将根据目标对象d的本质进行分派COM objectsCOM对象If d is a COM object, the operation is dispatched dynamically through COM IDispatch. This allows calling to COM types that dont have a Primary Interop Assembly (PIA), and relying on COM features that dont have a counterpart in C#, such as indexed properties and default properties.如果d是一个COM对象,则操作通过COM IDispatch进行动态分派。这允许调用没有主互操作程序集(Primary Interop Assembly,PIA)的COM类型,并依赖C#中没有对应概念的COM特性,如索引属性和默认属性。Dynamic objects动态对象If d implements the interface IDynamicObject d itself is asked to perform the operation. Thus by implementing IDynamicObject a type can completely redefine the meaning of dynamic operations. This is used intensively by dynamic languages such as IronPython and IronRuby to implement their own dynamic object models. It will also be used by APIs, e.g. by the HTML DOM to allow direct access to the objects properties using property syntax.如果d实现了IDynamicObject接口,则请求d自身来执行该操作。因此通过实现IDynamicObject接口,类型可以完全重新定义动态操作的意义。这在动态语言如IronPython和IronRuby中大量使用,用于实现他们的动态对象模型。API也会使用这类对象,例如HTML DOM允许直接使用属性语法来访问对象的属性。Plain objects简单对象Otherwise d is a standard .NET object, and the operation will be dispatched using reflection on its type and a C# “runtime binder” which implements C#s lookup and overload resolution semantics at runtime. This is essentially a part of the C# compiler running as a runtime component to “finish the work” on dynamic operations that was deferred by the static compiler.除此之外,则d是一个标准的.NET对象,操作是通过在其类型上进行反射来分派的,C#的“运行时绑定器(runtime binder)”实现了运行时的C#查找和重载解析。其背后的本质是将C#编译器作为运行时组件运行,来“完成”被静态编译器延迟的动态操作。Example示例Assume the following code:考虑下面的代码view plaincopy to clipboardprint? dynamicd1=newFoo(); dynamicd2=newBar(); strings; d1.M(s,d2,3,null);Because the receiver of the call to M is dynamic, the C# compiler does not try to resolve the meaning of the call. Instead it stashes away information for the runtime about the call. This information (often referred to as the “payload”) is essentially equivalent to:由于对M进行调用的接受者是dynamic类型的,C#编译器不会试图解析该调用的意义。而是将有关该调用的信息存储起来,供运行时使用。该信息(通常称作“有效载荷”)本质上等价于“Perform an instance method call of M with the following arguments: 1. a string 2. a dynamic 3. a literal int 3 4. a literal object null” “使用下面的参数执行一个称作M的实例方法 1. 一个string 2. 一个dynamic 3. 一个int字面值3 4. 一个object字面值null” At runtime, assume that the actual type Foo of d1 is not a COM type and does not implement IDynamicObject. In this case the C# runtime binder picks up to finish the overload resolution job based on runtime type information, proceeding as follows:在运行时,假设d1的实际类型Foo不是COM类型,也没有实现IDynamicObject。在这种情况下,C#运行时绑定器担负起了重载解析的工作,这是基于运行时类型信息完成的,按照下面的步骤进行处理 1. Reflection is used to obtain the actual runtime types of the two objects, d1 and d2, that did not have a static type (or rather had the static type dynamic). The result is Foo for d1 and Bar for d2. 2. Method lookup and overload resolution is performed on the type Foo with the call M(string,Bar,3,null) using ordinary C# semantics. 3. If the method is found it is invoked; otherwise a runtime exception is thrown. 1. 使用反射获取两个对象d1和d2的实际运行时类型,它们没有静态类型(包括静态类型dynamic)。结果为d1是Foo类型而d2是Bar。 2. 使用普通的C#语义在Foo类型上对M(string,Bar,3,null)调用进行方法查找和重载解析。 3. 如果找到了该方法,则调用它;否则抛出运行时异常。 Overload resolution with dynamic arguments带有动态参数的重载解析Even if the receiver of a method call is of a static type, overload resolution can still happen at runtime. This can happen if one or more of the arguments have the type dynamic:即便方法调用的接受者是静态类型的,重载解析依然发生在运行时。当一个或多个实参是dynamic类型时就会出现这种情况view plaincopy to clipboardprint? Foofoo=newFoo(); dynamicd=newBar(); varresult=foo.M(d);The C# runtime binder will choose between the statically known overloads of M on Foo, based on the runtime type of d, namely Bar. The result is again of type dynamic.C#运行时绑定器会基于d的运行时类型也就是Bar在Foo上M方法的静态可知(statically known)重载之间进行选择。其结果是dynamc类型。The Dynamic Language Runtime动态语言运行时An important component in the underlying implementation of dynamic lookup is the Dynamic Language Runtime (DLR), which is a new API in .NET 4.0.动态语言运行时(Dynamic Language Runtime,DLR)是动态查找的底层实现的一个重要组件,也是.NET 4.0中新增的API。The DLR provides most of the infrastructure behind not only C# dynamic lookup but also the implementation of several dynamic programming languages on .NET, such as IronPython and IronRuby. Through this common infrastructure a high degree of interoperability is ensured, but just as importantly the DLR provides excellent caching mechanisms which serve to greatly enhance the efficiency of runtime dispatch.DLR不仅为C#动态查找,还为很多其他.NET上的动态语言如IronPython和IronRuby的实现提供了底层的基础设施。这一通用基础设施确保了高度的互操作性,更重要的是,DLR提供了卓越的缓存机制,使得运行时分派的效率得到巨大的改善。To the user of dynamic lookup in C#, the DLR is invisible except for the improved efficiency. However, if you want to implement your own dynamically dispatched objects, the IDynamicObject interface allows you to interoperate with the DLR and plug in your own behavior. This is a rather advanced task, which requires you to understand a good deal more about the inner workings of the DLR. For API writers, however, it can definitely be worth the trouble in order to vastly improve the usability of e.g. a library representing an inherently dynamic domain.对于使用C#动态查找的用户来说,除了更高的性能之外,根本感觉不到DLR的存在。不过,如果你希望实现自己的动态分派对象,可以使用IDynamicObject接口来与DLR互操作,并向其中插入自己的行为。这是一个非常高级的任务,要求对DLR的内部工作原理有相当深入的了解。对于编写API的人,值得在这些问题上花些功夫,这样能够更广泛地改善可用性,例如为一个本身就是动态的领域编写类库。Open issues已知问题There are a few limitations and things that might work differently than you would expect.这里可能有一些限制或与你期望的结果不同。 The DLR allows objects to be created from objects that represent classes. However, the current implementation of C# doesnt have syntax to support this. Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload. Anonymous functions (i.e. lambda expressions) cannot appear as arguments to a dynamic method call. The compiler cannot bind (i.e. “understand”) an anonymous function without knowing what type it is converted to. DLR允许从一个表示类的对象创建对象。然而,C#的当前实现还不具备支持这一功能的语法。 动态查找不能查找扩展方法。不论扩展方法是否依赖该调用的静态上下文(也就是出现了using语句),因为该上下文信息并不会作为有效载荷的一部分保留下来。 匿名函数(也就是lambda表达式)不能作为实参传递给动态方法调用。在不知道要转换成什么类型的情况下,编译器不能绑定(也就是“理解”)一个匿名函数。 One consequence of these limitations is that you cannot easily use LINQ queries over dynamic objects:这些限制导致的结果就是很难在动态对象上使用LINQ查询view plaincopy to clipboardprint? dynamiccollection=.; varresult=collection.Select(e=e+5);If the Select method is an extension method, dynamic lookup will not find it. Even if it is an instance method, the above does not compile, because a lambda expression cannot be passed as an argument to a dynamic operation.如果Selected方法是个扩展方法,动态查找将找不到它。即便它是一个实例方法,上面的代码也无法编译,因为lambda表达式不能作为参数传递给动态操作。There are no plans to address these limitations in C# 4.0.在C# 4.0中没有计划解决这些限制。Named and Optional Arguments命名参数和可选参数Named and optional parameters are really two distinct features, but are often useful together. Optional parameters allow you to omit arguments to member invocations, whereas named arguments is a way to provide an argument using the name of the corresponding parameter instead of relying on its position in the parameter list.命名参数和可选参数是两个截然不同的功能,但通常一起使用。在进行成员调用时,可以忽略可选参数;而命名参数的方式可以通过名称来提供一个参数,而无需依赖它在参数列表中出现的位置。Some APIs, most notably COM interfaces such as the Office automation APIs, are written specifically with named and optional parameters in mind. Up until now it has been very painful to call into these APIs from C#, with sometimes as many as thirty arguments having to be explicitly passed, most of which have reasonable default values and could be omitted.有些API尤其是COM接口如Office自动化API确实本身就是通过命名参数和可选参数编写的。之前在C#中调用这些API非常痛苦,尤其有的时候需要多达30几个参数都必须显式传递,而其中大多数都具有合理的默认值,是

温馨提示

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

评论

0/150

提交评论