您的位置:首页 > 移动开发

Microsoft .NET Framework 2.0 Application Development Foundation 翻译系列5(第一章:第二课公共引用类型的使用①)

2006-12-08 22:20 671 查看

Lesson2:UsingCommonReferenceTypes

公共引用类型的使用

Mosttypesinthe.NETFrameworkarereferencetypes.Referencetypesprovideagreatdealofflexibility,andtheyofferexcellentperformancewhenpassingthemtomethods.Thefollowingsectionsintroducereferencetypesbydiscussingcommonbuilt-inclasses.Lesson4,"ConvertingBetweenTypes,"coverscreatingclasses,interfaces,anddelegates.

在.net中的大部分类型都是引用类型.引用类型提供了强大的灵活性,并且当将它们传递给方法时,它们提供了非常好的性能.下面通过描述公共默认类来介绍引用类型.在第四课”类之间的转换”中包含了建立类,接口,和代理(委托)的介绍。

Afterthislesson,youwillbeableto:课后你将可以

·Explainthedifferencebetweenvaluetypesandreferencetypes.

·描述值类型和引用类型之间的不同

·Describehowvaluetypesandreferencetypesdifferwhenassigningvalues.

·描述给值类型和引用类型赋值时的区别

·Listthebuilt-inreferencetypes.

·默认引用类型列表

·DescribewhenyoushouldusetheStringBuildertype.

·描述StringBuilder类型的使用

·Createandsortarrays.

·建立和存储数组

·Open,read,write,andclosefiles.

·打开,读写和关闭文件

·Detectwhenexceptionsoccurandrespondtotheexception.

·发现并处理异常

Estimatedlessontime:40minutes课时:40分钟

WhatIsaReferenceType?什么是引用类型?

Referencetypesstoretheaddressoftheirdata,alsoknownasapointer,onthestack.Theactualdatathataddressreferstoisstoredinanareaofmemorycalledtheheap.Theruntimemanagesthememoryusedbytheheapthroughaprocesscalledgarbagecollection.Garbagecollectionrecoversmemoryperiodicallyasneededbydisposingofitemsthatarenolongerreferenced.

引用类型存储的是它们数据的地址,类似栈中的指针.而真实数据,即它引用的存储地址则是在一个叫做堆的内存区域中.堆在内存中的使用由一个叫gc(垃圾回收器)的程序在运行时进行管理.

BestPractices—Garbagecollection

GarbagecollectionoccursonlywhenneededorwhentriggeredbyacalltoGC.Collect.Automaticgarbagecollectionisoptimizedforapplicationswheremostinstancesareshort-lived,exceptforthoseallocatedatthebeginningoftheapplication.Followingthatdesignpatternwillresultinthebestperformance.

垃圾回收器只有在需要或通过GC.Collect调用的时候才会执行.除非那些实例在应用程序开始时就已经定义了,否则垃圾回收会自动对应用程序中短期存在的大量实例进行优化处理.

ComparingtheBehaviorofReferenceandValueTypes

值类型和引用行为的比较

Becausereferencetypesrepresenttheaddressofdataratherthanthedataitself,assigningonereferencevariabletoanotherdoesn'tcopythedata.Instead,assigningareferencevariabletoanotherinstancemerelycreatesasecondcopyofthereference,whichreferstothesamememorylocationontheheapastheoriginalvariable.

因为引用类型表示的是数据的地址而不是数据本身,所以将一个引用类型赋给另一个引用类型并不会拷贝数据.只是建立了这个引用的一份拷贝,它们指向的是与原始变量相同的内存位置.

Considerthefollowingsimplestructuredeclaration:考虑下面简单的结构声明

'VB

StructureNumbers

PublicvalAsInteger


PublicSubNew(ByVal_valAsInteger)

val=_val

EndSub


PublicOverloadsOverridesFunctionToString()AsString

Returnval.ToString

EndFunction

EndStructure


//C#

structNumbers

{

publicintval;


publicNumbers(int_val)

{val=_val;}


publicoverridestringToString()

{returnval.ToString();}

}

Nowconsiderthefollowingcode,whichcreatesaninstanceoftheNumbersstructure,copiesthatstructuretoasecondinstance,modifiesbothvalues,anddisplaystheresults:

现在考虑建立一个Numbers结构的实例,然后将它赋给另一个实例,将两个实例的值都进行修改并输出结果.

'VB

Dimn1AsNumbers=NewNumbers(0)

Dimn2AsNumbers=n1

n1.val+=1

n2.val+=2

Console.WriteLine("n1={0},n2={1}",n1,n2)


//C#

Numbersn1=newNumbers(0);

Numbersn2=n1;

n1.val+=1;

n2.val+=2;

Console.WriteLine("n1={0},n2={1}",n1,n2);

Thiscodewoulddisplay"n1=1,n2=2"becauseastructureisavaluetype,andcopyingavaluetyperesultsintwodistinctvalues.However,ifyouchangetheNumberstypedeclarationfromastructuretoaclass,thesameapplicationwoulddisplay"n1=3,n2=3".ChangingNumbersfromastructuretoaclasscausesittobeareferencetyperatherthanavaluetype.Whenyoumodifyareferencetype,youmodifyallcopiesofthatreferencetype.

代码结果显示"n1=1,n2=2",因为结构是一个值类型,并且复制的只是两个不同值中的结果.可是,如果你将Numbers的声明从结构改为类,那么结果将显示"n1=3,n2=3",这种改变导致它变为一个引用类型.当你改变一个引用类型时,你修改的是这个引用类型的所有拷贝内容.

Built-inReferenceTypes

Thereareabout2500built-inreferencetypesinthe.NETFramework.EverythingnotderivedfromSystem.ValueTypeisareferencetype,includingthese2500orsobuilt-inreferencetypes.Table1-3liststhemostcommonlyusedtypes,fromwhichmanyotherreferencetypesarederived.

在.net框架中有大约2500个引用类型.在这其中,并不是每一个引用类型都来源于”System.ValueType”.表1-3列出了许多来源于其它引用类型的常用类型.

Table1-3:CommonReferenceTypes

Type

Usefor

System.Object

TheObjecttypeisthemostgeneraltypeintheFramework.YoucanconvertanytypetoSystem.Object,andyoucanrelyonanytypehavingToString,GetType,andEqualsmembersinheritedfromthistype.

这个object类型在net框架中是最常用的类型.你可以将任何类型转换为System.Object,并且你使用的ToString(),GetType(),和Equals方法都是从这个类型继承来的.

System.String

Textdata.文本数据

System.Text.StringBuilder

Dynamictextdata.动态文本数据

System.Array

Arraysofdata.Thisisthebaseclassforallarrays.Arraydeclarationsuselanguage-specificarraysyntax.

数据数组.这是所有数组的基类.数组按照特定语言的数组语法进行声明

System.IO.Stream

Bufferforfile,device,andnetworkI/O.Thisisanabstractbaseclass;task-specificclassesarederivedfromStream.

缓冲文件、驱动和网络的输入输出数据流。这是一个抽象基类;所有的来源于stream的类都继承于这个类

System.Exception

Handlingsystemandapplication-definedexceptions.Task-specificexceptionsinheritfromthistype.

处理系统和已定义的应用程序异常。所有异常都继承自这个类

StringsandStringBuilders

String和StringBuilders

Typesaremorethanjustcontainersfordata,theyalsoprovidethemeanstomanipulatethatdatathroughtheirmembers.System.Stringprovidesasetofmembersforworkingwithtext.Forexample,thefollowingcodedoesaquicksearchandreplace:

类型不仅仅是数据的容器,它们也提供了巧妙的处理数据的方法.象System.String就为文本数据提供了一组处理方法.举例来说,下面代码用来执行一个快速的搜索和替换.

'VB

DimsAsString="thisissometexttosearch"

s=s.Replace("search","replace")

Console.WriteLine(s)


//C#

strings="thisissometexttosearch";

s=s.Replace("search","replace");

Console.WriteLine(s);


StringsoftypeSystem.Stringareimmutablein.NET.Thatmeansanychangetoastringcausestheruntimetocreateanewstringandabandontheoldone.Thathappensinvisibly,andmanyprogrammersmightbesurprisedtolearnthatthefollowingcodeallocatesfournewstringsinmemory:

在.net框架中使用System.String类型定义的字符串是不变的.这句话的意思是说任何对一个字符串的改变都会导致在运行时建立一个新的字符串并且将原来的字符串丢弃.这种过程是不可见的.并且许多程序员会惊讶的发现下面的代码将会在内存中产生4个新的字符串.

'VB

DimsAsString


s="wombat"'"wombat"

s+="kangaroo"'"wombatkangaroo"

s+="wallaby"'"wombatkangaroowallaby"

s+="koala"'"wombatkangaroowallabykoala"

Console.WriteLine(s)


//C#

strings;


s="wombat";//"wombat"

s+="kangaroo";//"wombatkangaroo"

s+="wallaby";//"wombatkangaroowallaby"

s+="koala";//"wombatkangaroowallabykoala"

Console.WriteLine(s);

Onlythelaststringhasareference;theotherthreewillbedisposedofduringgarbagecollection.Avoidingthesetypesoftemporarystringshelpsavoidunnecessarygarbagecollection,whichimprovesperformance.Thereareseveralwaystoavoidtemporarystrings:

引用的只是最后一个字符串.其它三个在GC(垃圾回收器)运行时被释放了.为了避免因为产生这些临时的字符串而进行的不必要的垃圾回收,从而改善性能.下面是几种避免临时字符串产生的途径.

·UsetheStringclass'sConcat,Join,orFormatmethodstojoinmultipleitemsinasinglestatement.

·使用String类的Concat方法、Join或Format方法来进行追加、连接或替换字符串。

·UsetheStringBuilderclasstocreatedynamic(mutable)strings.

·使用StringBuilder类来建立动态字符串

TheStringBuildersolutionisthemostflexiblebecauseitcanspanmultiplestatements.Thedefaultconstructorcreatesabuffer16byteslong,whichgrowsasneeded.Youcanspecifyaninitialsizeandamaximumsizeifyoulike.ThefollowingcodedemonstratesusingStringBuilder:

StringBuilder方案是最灵活的,因为它可以使用在不同的变量之间。默认构造器会建立一个根据需要变化的16bytes长度的缓存。如果你喜欢的话,你还可以指定初始范围和最大范围。下面示范了StringBuilder的使用。

'VB

DimsbAsNewSystem.Text.StringBuilder(30)

sb.Append("wombat")'Buildstring.

sb.Append("kangaroo")

sb.Append("wallaby")

sb.Append("koala")

DimsasString=sb.ToString'Copyresulttostring.

Console.WriteLine(s)


//C#

System.Text.StringBuildersb=newSystem.Text.StringBuilder(30);

sb.Append("wombat");//Buildstring.

sb.Append("kangaroo");

sb.Append("wallaby");

sb.Append("koala");

strings=sb.ToString();//Copyresulttostring.

Console.WriteLine(s);

AnothersubtlebutimportantfeatureoftheStringclassisthatitoverridesoperatorsfromSystem.Object.Table1-4liststheoperatorstheStringclassoverrides.

String类的另一个重要的特点是它覆盖了System.Object的操作符(Operator)。表1-4列出了被覆盖的操作符。

Table1-4:StringOperators

Operator

VisualBasic

C#

ActiononSystem.String

Addition

+or&

+

Joinstwostringstocreateanewstring.

将两个字符串合并为一个新的字符串

Equality

=

==

ReturnsTrueiftwostringshavethesamecontents;Falseiftheyaredifferent.

如果两个字符串有相同的内容则返回true;不同则返回false

Inequality

<>

!=

Theinverseoftheequalityoperator.

与Equality相反的判断,不相等的函数。

Assignment

=

=

Copiesthecontentsofonestringintoanewone.Thiscausesstringstobehavelikevaluetypes,eventhoughtheyareimplementedasreferencetypes.

将一个字符串内容复制给一个新的字符串,虽然它们是引用类型,但这个过程类似值类型。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐