C#40新特性.docx

上传人:b****0 文档编号:10062597 上传时间:2023-05-23 格式:DOCX 页数:44 大小:48.74KB
下载 相关 举报
C#40新特性.docx_第1页
第1页 / 共44页
C#40新特性.docx_第2页
第2页 / 共44页
C#40新特性.docx_第3页
第3页 / 共44页
C#40新特性.docx_第4页
第4页 / 共44页
C#40新特性.docx_第5页
第5页 / 共44页
C#40新特性.docx_第6页
第6页 / 共44页
C#40新特性.docx_第7页
第7页 / 共44页
C#40新特性.docx_第8页
第8页 / 共44页
C#40新特性.docx_第9页
第9页 / 共44页
C#40新特性.docx_第10页
第10页 / 共44页
C#40新特性.docx_第11页
第11页 / 共44页
C#40新特性.docx_第12页
第12页 / 共44页
C#40新特性.docx_第13页
第13页 / 共44页
C#40新特性.docx_第14页
第14页 / 共44页
C#40新特性.docx_第15页
第15页 / 共44页
C#40新特性.docx_第16页
第16页 / 共44页
C#40新特性.docx_第17页
第17页 / 共44页
C#40新特性.docx_第18页
第18页 / 共44页
C#40新特性.docx_第19页
第19页 / 共44页
C#40新特性.docx_第20页
第20页 / 共44页
亲,该文档总共44页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

C#40新特性.docx

《C#40新特性.docx》由会员分享,可在线阅读,更多相关《C#40新特性.docx(44页珍藏版)》请在冰点文库上搜索。

C#40新特性.docx

C#40新特性

[翻译]C#4.0新特性(白皮书)

原文地址:

原著作者:

MadsTorgersen,C#LanguagePM

翻译:

AndersLiu

摘要:

MicrosoftVisualC#3.0作为VisualStudio2008的一部分发布以来已经快一年了。

在VSManagedLanguages团队,我们一直努力创建该语言的下一个版本(没什么惊喜,就是C#4.0),而这个文档是我们现在所看到的、计划中的语言特性的第一个公开描述。

Contents

目录

∙Introduction简介

oC#4.0

∙DynamicLookup动态查找

oThedynamictypedynamic类型

oDynamicoperations动态操作

oRuntimelookup运行时查找

oExample示例

oOverloadresolutionwithdynamicarguments带有动态参数的重载解析

oTheDynamicLanguageRuntime动态语言运行时

oOpenissues已知问题

∙NamedandOptionalArguments命名参数和可选参数

oOptionalparameters可选参数

oNamedandoptionalarguments命名的和可选的实参

oOverloadresolution重载解析

∙FeaturesforCOMinteropCOM互操作特性

oDynamicimport动态引入

oCompilingwithoutPIAs无PIA的编译

oOmittingref省略ref

oOpenissues已知问题

∙Variance变性

oCovariance协变性

oContravariance逆变性

oLimitations限制

∙COMExampleCOM示例

∙RelationshipwithVisualBasic与VisualBasic的关系

∙Resources资源

Introduction

简介

ItisnowclosetoayearsinceMicrosoftVisualC#3.0shippedaspartofVisualStudio2008.IntheVSManagedLanguagesteamwearehardatworkoncreatingthenextversionofthelanguage(withtheunsurprisingworkingtitleofC#4.0),andthisdocumentisafirstpublicdescriptionoftheplannedlanguagefeaturesaswecurrentlyseethem.

MicrosoftVisualC#3.0作为VisualStudio2008的一部分发布以来已经快一年了。

在VSManagedLanguages团队,我们一直努力创建该语言的下一个版本(没什么惊喜,就是C#4.0),而这个文档是我们现在所看到的、计划中的语言特性的第一个公开描述。

Pleasebeadvisedthatallthisisinearlystagesofproductionandissubjecttochange.Partofthereasonforsharingourplansinpublicsoearlyispreciselytogetthekindoffeedbackthatwillcauseustoimprovethefinalproductbeforeitrollsout.

请记住本文内容都是针对产品早期的,而且将来会改变。

这么早地共享我们的计划,一部分原因是为了获取某些反馈,这些反馈会让我们在产品最终发布出来之前改进它。

Simultaneouslywiththepublicationofthiswhitepaper,afirstpublicCTP(communitytechnologypreview)ofVisualStudio2010isgoingoutasaVirtualPCimageforeveryonetotry.Pleaseuseittoplayandexperimentwiththefeatures,andletusknowofanythoughtsyouhave.Weaskforyourunderstandingandpatienceworkingwithveryearlybits,whereespeciallynewornewlyimplementedfeaturesdonothavethequalityorstabilityofafinalproduct.TheaimoftheCTPisnottogiveyouaproductiveworkenvironmentbuttogiveyouthebestpossibleimpressionofwhatweareworkingonforthenextrelease.

与该白皮书一同发布的还有VisualStudio2010的第一个公开的CTP(社区技术预览),它通过VirtualPC映像发布,任何人都可以试用。

请使用这个CTP来把玩和试验这些特性,并让我们知道您的想法。

我们希望知道您对这个早期产品的理解和不满,尤其是新添加的实现特性是否不具备最终产品应有的质量和稳定性。

这个CTP的目的不是为您提供一个高生产力的工作环境,而是让您对我们正在为下一个发布版做些什么有个印象。

TheCTPcontainsanumberofwalkthroughs,someofwhichhighlightthenewlanguagefeaturesofC#4.0.Thoseareexcellentforgettingahands-onguidedtourthroughthedetailsofsomecommonscenariosforthefeatures.Youmayconsiderthiswhitepaperacompaniondocumenttothesewalkthroughs,complementingthemwithafocusontheoveralllanguagefeaturesandhowtheywork,asopposedtothespecificsoftheconcretescenarios.

该CTP包含了大量的演练,其中一些着重于C#4.0的语言新特性。

要详细了解这些特性的常用场景,这些演练是绝好的上手教程。

您可以认为该白皮书是这些演练的伴随文档,全面地介绍了语言的特性和工作原理,而那些演练则是介绍具体的场景。

C#4.0

ThemajorthemeforC#4.0isdynamicprogramming.Increasingly,objectsare“dynamic”inthesensethattheirstructureandbehaviorisnotcapturedbyastatictype,oratleastnotonethatthecompilerknowsaboutwhencompilingyourprogram.Someexamplesinclude

C#4.0的主要主题是动态编程。

对象的意义变得越来越“动态”,它们的结构和行为无法通过静态类型来捕获,或者至少编译器在编译程序时无法得知对象的结构和行为。

例如——

∙a.objectsfromdynamicprogramminglanguages,suchasPythonorRuby

∙b.COMobjectsaccessedthroughIDispatch

∙c.ordinary.NETtypesaccessedthroughreflection

∙d.objectswithchangingstructure,suchasHTMLDOMobjects

∙a.来自动态编程语言——如Python或Ruby——的对象

∙b.通过IDispatch访问的COM对象

∙c.通过反射访问的一般.NET类型

∙d.结构发生过变化的对象——如HTMLDOM对象

WhileC#remainsastaticallytypedlanguage,weaimtovastlyimprovetheinteractionwithsuchobjects.

尽管C#依然是静态类型语言,但我们的目的是改善它与这些对象的交互。

Asecondarythemeisco-evolutionwithVisualBasic.Goingforwardwewillaimtomaintaintheindividualcharacterofeachlanguage,butatthesametimeimportantnewfeaturesshouldbeintroducedinbothlanguagesatthesametime.Theyshouldbedifferentiatedmorebystyleandfeelthanbyfeatureset.

另一个次要主题是与VisualBasic协同进步(co-evolution)。

将来我们希望仅维护每种语言单独的特征,而重要的新特性会同时引入两种语言。

它们的区别仅仅是风格和感觉上的,而不在于特性集方面。

ThenewfeaturesinC#4.0fallintofourgroups:

C#4.0中的新特性分为四组——

Dynamiclookup

动态查找

Dynamiclookupallowsyoutowritemethod,operatorandindexercalls,propertyandfieldaccesses,andevenobjectinvocationswhichbypasstheC#statictypecheckingandinsteadgetsresolvedatruntime.

动态查找允许在编写方法、运算符和索引器调用、属性和字段访问甚至对象调用时,绕过C#静态类型检查,而在运行时进行解析。

Namedandoptionalparameters

命名参数和可选参数

ParametersinC#cannowbespecifiedasoptionalbyprovidingadefaultvaluefortheminamemberdeclaration.Whenthememberisinvoked,optionalargumentscanbeomitted.Furthermore,anyargumentcanbepassedbyparameternameinsteadofposition.

现在C#中的参数可以通过在成员声明中为其提供默认值来指名它是可选的。

在调用该成员时,可选参数可以忽略。

另外,在传入任何参数时都可以按照参数名而不是位置进行传递。

COMspecificinteropfeatures

特定于COM的互操作特性

DynamiclookupaswellasnamedandoptionalparametersbothhelpmakingprogrammingagainstCOMlesspainfulthantoday.Ontopofthat,however,weareaddinganumberofothersmallfeaturesthatfurtherimprovetheinteropexperience.

动态查找以及命名参数和可选参数都有助于使针对COM的编程不再像今天这样痛苦。

在这些特性之上,我们还添加了大量其他小特性,进一步改善了互操作体验。

Variance

变性

ItusedtobethatanIEnumerablewasn’tanIEnumerable.Nowitis–C#embracestypesafe“co-andcontravariance”andcommonBCLtypesareupdatedtotakeadvantageofthat.

过去,IEnumerable并不是IEnumerable

现在它是了——C#包含了类型安全的“协变性和逆变性(co-andcontravariance)”而且通用的BCL也将利用这一特性进行更新。

DynamicLookup

动态查找

Dynamiclookupallowsyouaunifiedapproachtoinvokingthingsdynamically.Withdynamiclookup,whenyouhaveanobjectinyourhandyoudonotneedtoworryaboutwhetheritcomesfromCOM,IronPython,theHTMLDOMorreflection;youjustapplyoperationstoitandleaveittotheruntimetofigureoutwhatexactlythoseoperationsmeanforthatparticularobject.

动态查找可以用统一的方式来动态调用成员。

有了动态查找,当你拿到一个对象时,不用管它是来自于COM还是IronPython、HTMLDOM或是反射;只需要对其进行操作即可,运行时会帮你指出针对特定的对象,这些操作的具体意义。

Thisaffordsyouenormousflexibility,andcangreatlysimplifyyourcode,butitdoescomewithasignificantdrawback:

Statictypingisnotmaintainedfortheseoperations.Adynamicobjectisassumedatcompiletimetosupportanyoperation,andonlyatruntimewillyougetanerrorifitwasn’tso.Oftentimesthiswillbenoloss,becausetheobjectwouldn’thaveastatictypeanyway,inothercasesitisatradeoffbetweenbrevityandsafety.Inordertofacilitatethistradeoff,itisadesigngoalofC#toallowyoutooptinoroptoutofdynamicbehavioroneverysinglecall.

这给你带来了巨大的灵活性,并能极大程度地精简代码,但它伴随着一个巨大的缺点——不会为这些操作维护静态类型。

在编译时,会假设动态对象支持任何操作,而如果它不支持某个操作,则只有到运行时才能得到错误。

有的时候这不会有任何损失,因为对象根本不具有静态类型,而且他情况下必须在简洁和安全之间进行权衡。

为了帮助进行权衡,C#的一个设计目标就是允许在每个单独的调用中选择是否使用动态行为。

Thedynamictype

dynamic类型

C#4.0introducesanewstatictypecalleddynamic.Whenyouhaveanobjectoftypedynamicyoucan“dothingstoit”thatareresolvedonlyatruntime:

C#4.0引入了一个新的静态类型,称为dynamic。

当你拥有了一个dynamic类型的对象后,你“对他做的事情”只会在运行时进行解析——

viewplaincopytoclipboardprint?

∙dynamic d = GetDynamicObject(...);  

∙d.M(7);  

TheC#compilerallowsyoutocallamethodwithanynameandanyargumentsondbecauseitisoftypedynamic.Atruntimetheactualobjectthatdreferstowillbeexaminedtodeterminewhatitmeansto“callMwithanint”onit.

C#编译器允许你使用任何参数在d上调用一个方法,因为它的类型是dynamic。

运行时会检查d的实际类型,并检测在它上面“用一个int调用M”是什么意思。

Thetypedynamiccanbethoughtofasaspecialversionofthetypeobject,whichsignalsthattheobjectcanbeuseddynamically.Itiseasytooptinoroutofdynamicbehavior:

anyobjectcanbeimplicitlyconvertedtodynamic,“suspendingbelief”untilruntime.Conversely,thereisan“assignmentconversion”fromdynamictoanyothertype,whichallowsimplicitconversioninassignment-likeconstructs:

可以认为dynamic类型是object类型的一个特殊版本,指出了对象可以动态地使用。

选择是否使用动态行为很简单——任何对象都可以隐式转换为dynamic,“挂起信任”直到运行时。

反之,从dynamic到任何其他类型都存在“赋值转换”,可以类似于赋值的结构中进行隐式转换——

viewplaincopytoclipboardprint?

∙dynamic d = 7; // implicit conversion  

∙int i = d; // assignment conversion  

Dynamicoperations

动态操作

Notonlymethodcalls,butalsofieldandpropertyaccesses,indexerandoperatorcallsandevendelegateinvocationscanbedispatcheddynamically:

不仅是方法调用,字段和属性访问、索引器和运算符调用甚至委托调用都可以动态地分派——

viewplaincopytoclipboardprint?

∙dynamic d = GetDynamicObject(…);  

∙d.M(7); // calling methods  

∙d.f = d.P; // getting and settings fields and properties  

∙d[“one”] = d[“two”]; // getting and setting thorugh indexers  

∙int i = d + 3; // calling operators  

∙string s = d(5,7); // invoking as a delegate  

TheroleoftheC#compilerhereissimplytopackageupthenecessaryinformationabout“whatisbeingdonetod”,sothattheruntimecanpickitupanddeterminewhattheexactmeaningofitisgivenanactualobjectd.Thinkofitasdeferringpartofthecompiler’sjobtoruntime.

C#编译器在这里的角色就是打包有关“在d上做什么”的必要信息,使得运行时可以获取这些信息并检测对于实际对象d这些操作的确切含义。

可以认为这是将编译器的部分工作延迟到了运行时。

Theresultofanydynamicoperationisitselfoftypedynamic.

任何动态操作的结果本身也是dynamic类型的。

Runtimelookup

运行时查找

Atruntimeadynamicoperationisdispatchedaccordingtothenatureofitstargetobjectd:

在运行时,动态操作将根据目标对象d的本质进行分派——

COMobjects

COM对象

IfdisaCOMobject,theoperationisdispatcheddynamicallythroughCOMIDispatch.ThisallowscallingtoCOMtypesthatdon’thaveaPrimaryI

展开阅读全文
相关搜索

当前位置:首页 > 医药卫生 > 基础医学

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2