Tải bản đầy đủ - 0 (trang)
8 Add, Subtract, and Compare Dates and Times

8 Add, Subtract, and Compare Dates and Times

Tải bản đầy đủ - 0trang

reference.



reference.



Addition(+)



AddstwoTimeSpan

instances.



AddsaTimeSpantoa

DateTime.



Subtraction(-)



SubtractsaTimeSpanor

SubtractsoneTimeSpan

aDateTimefroma

instancefromanother.

DateTime.



Equality(==)



ComparestwoTimeSpan ComparestwoDateTime

instancesandreturnstrue instancesandreturns

iftheyareequal.

trueiftheyareequal.



Inequality(!=)



ComparestwoTimeSpan ComparestwoDateTime

instancesandreturnstrue instancesandreturns

iftheyaren'tequal.

trueiftheyaren'tequal.



Determinesifone

Determinesifone

GreaterThan(>) TimeSpanisgreaterthan DateTimeisgreaterthan

anotherTimeSpan.

anotherDateTime.

Determinesifone

GreaterThanor TimeSpanisgreaterthan

Equal(>=)

orequaltoanother

TimeSpan.



Determinesifone

DateTimeisgreaterthan

orequaltoanother

DateTime.



LessThan(<)



Determinesifone

TimeSpanislessthan

anotherTimeSpan.



Determinesifone

DateTimeislessthan

anotherDateTime.



LessThanor

Equal(<=)



Determinesifone

TimeSpanislessthanor

equaltoanother

TimeSpan.



Determinesifone

DateTimeislessthanor

equaltoanother

DateTime.



ReturnsaTimeSpanwith

UnaryNegation

anegatedvalueofthe

NotSupported.

(-)

specifiedTimeSpan.

UnaryPlus(+)



ReturnstheTimeSpan

specified.



NotSupported.



TheDateTimestructurealsoimplementsthemethodsAddTicks,

AddMilliseconds,AddSeconds,AddMinutes,AddHours,AddDays,

AddMonths,andAddYears.Eachofthesemethodsallowsyoutoadd(or

subtractusingnegativevalues)theappropriateelementoftimetoa

DateTimeinstance.ThesemethodsandtheoperatorslistedinTable2.4

don'tmodifytheoriginalDateTime—insteadtheycreateanewinstance

withthemodifiedvalue.Thefollowingcodedemonstratestheuseof

operatorstomanipulatetheDateTimeandTimeSpanstructures.

//CreateaTimeSpanrepresenting2.5days

TimeSpantimespan1=newTimeSpan(2,12,0,0);

//CreateaTimeSpanrepresenting4.5days

TimeSpantimespan2=newTimeSpan(4,12,0,0);

//CreateaTimeSpanrepresenting1week

TimeSpanoneWeek=timespan1+timespan2;

//CreateaDateTimewiththecurrentdateandtime

DateTimenow=DateTime.Now;

//CreateaDateTimerepresenting1weekago

DateTimepast=now-oneWeek;

//CreateaDateTimerepresenting1weekinthefuture

DateTimefuture=now+oneWeek;



2.9SortanArrayoranArrayList

Problem

YouneedtosorttheelementscontainedinanarrayoranArrayList.



Solution

UsetheArrayList.SortmethodtosortArrayListobjectsandthestatic

Array.Sortmethodtosortarrays.



Discussion

ThesimplestSortmethodoverloadsortstheobjectscontainedinan

arrayorArrayListaslongastheobjectsimplementthe

System.IComparableinterfaceandareofthesametype—allofthebasic

datatypesimplementIComparable.Thefollowingcodeexcerpt

demonstrateshowtousetheSortmethod:

//Createanewarrayandpopulateit.

int[]array={4,2,9,3};

//Sortthearray

Array.Sort(array);

//Displaythecontentsofthesortedarray

foreach(intiinarray){Console.WriteLine(i);}

//CreateanewArrayListandpopulateit.

ArrayListlist=newArrayList(4);

list.Add("Michael");

list.Add("Kate");

list.Add("Andrea");

list.Add("Angus");

//SorttheArrayList

list.Sort();



//DisplaythecontentsofthesortedArrayList

foreach(stringsinlist){Console.WriteLine(s);}

Tosortobjectsthatdon'timplementIComparable,youmustpasstheSort

methodanobjectthatimplementstheSystem.Collections.IComparer

interface.TheIComparerimplementationmustbecapableofcomparing

theobjectscontainedwithinthearrayorArrayList.(Recipe16.3

describeshowtoimplementboththeIComparableandIComparer

interfaces.)



2.10CopyaCollectiontoanArray

Problem

Youneedtocopythecontentsofacollectiontoanarray.



Solution

UsetheICollection.CopyTomethodimplementedbyallcollection

classes,orusetheToArraymethodimplementedbytheArrayList,Stack,

andQueuecollections.



Discussion

TheICollection.CopyTomethodandtheToArraymethodperformroughly

thesamefunction—theyperformashallowcopyoftheelements

containedinacollectiontoanarray.ThekeydifferenceisthatCopyTo

copiesthecollection'selementstoanexistingarray,whereasToArray

createsanewarraybeforecopyingthecollection'selementsintoit.

TheCopyTomethodtakestwoarguments:anarrayandanindex.The

arrayisthetargetofthecopyoperationandmustbeofatype

appropriatetohandletheelementsofthecollection.Ifthetypesdon't

matchorthereisnoimplicitconversionpossiblefromthecollection

element'stypetothearrayelement'stype,a

System.InvalidCastExceptionisthrown.Theindexisthestartingelement

ofthearraywherethecollection'selementswillbecopied.Iftheindexis

equaltoorgreaterthanthelengthofthearray,orthenumberof

collectionelementsexceedsthecapacityofthearray,a

System.ArgumentExceptionisthrown.Thiscodeexcerptshowshowto

copythecontentsofanArrayListtoanarrayusingtheCopyTomethod.

//CreateanewArrayListandpopulateit.

ArrayListlist=newArrayList(5);

list.Add("Brenda");

list.Add("George");

list.Add("Justin");

list.Add("Shaun");



list.Add("Meaghan");

//Createastring[]andusetheICollection.CopyTomethodto

//copythecontentsoftheArrayList.

string[]array1=newstring[5];

list.CopyTo(array1,0);



TheArrayList,Stack,andQueueclassesalsoimplementtheToArray

method,whichautomaticallycreatesanarrayofthecorrectsizeto

accommodateacopyofalltheelementsofthecollection.Ifyoucall

ToArraywithnoarguments,itreturnsanobject[]regardlessofthetypeof

objectscontainedinthecollection.However,youcanpassa

System.TypeobjectthatspecifiesthetypeofarraythattheToArray

methodshouldcreate.(Youmustcastthereturnedstronglytypedarray

tothecorrecttype.)HereisanexampleofhowtousetheToArray

methodontheArrayListcreatedinthepreviouslisting.

//UseArrayList.ToArraytocreateanobject[]fromthecontent

//ofthecollection.

object[]array2=list.ToArray();



//UseArrayList.ToArraytocreateastronglytypedstring[]fr

//thecontentsofthecollection.

string[]array3=

(string[])list.ToArray(System.Type.GetType("System.String")



2.11CreateaStronglyTypedCollection

Problem

Youneedtocreateacollectionthatcanholdelementsonlyofaspecific

type.



Solution

CreateaclassthatderivesfromtheSystem.Collections.CollectionBase

orSystem.Collections.DictionaryBaseclasses,andimplementtype-safe

methodsforthemanipulationofthecollection.



Discussion

TheCollectionBaseandDictionaryBaseclassesprovideconvenientbase

classesfromwhichtoderivetype-safecollectionswithouthavingto

implementthestandardIDictionary,IList,ICollection,andIEnumerable

interfacesfromscratch.

CollectionBaseisforIList-basedcollections(suchasArrayList).

Internally,CollectionBasemaintainsthecollectionusingastandard

ArrayListobject,whichisaccessiblethroughtheprotectedpropertyList.

DictionaryBaseisforIDictionary-basedcollections(suchasHashtable).

Internally,DictionaryBasemaintainsthecollectionusingastandard

Hashtableobject,whichisaccessiblethroughtheprotectedproperty

Dictionary.Thefollowingcodeshowstheimplementationofastrongly

typedcollection(basedontheCollectionBaseclass)torepresentalistof

System.Reflection.AssemblyNameobjects.

usingSystem.Reflection;

usingSystem.Collections;

publicclassAssemblyNameList:CollectionBase{

publicintAdd(AssemblyNamevalue){

returnthis.List.Add(value);



}

publicvoidRemove(AssemblyNamevalue){

this.List.Remove(value);

}

publicAssemblyNamethis[intindex]{

get{

return(AssemblyName)this.List[index];

}

set{

this.List[index]=value;

}

}

publicboolContains(AssemblyNamevalue){

returnthis.List.Contains(value);

}

publicvoidInsert(intindex,AssemblyNamevalue){

this.List.Insert(index,value);

}

}

BoththeCollectionBaseandDictionaryBaseclassesimplementasetof

protectedmethodswiththeprefixOn*.Thesemethods—suchas

OnClear,OnClearComplete,OnGet,OnGetComplete,andsoon—are

intendedtobeoverriddenbyaderivedclassandallowyoutoimplement

anycustomfunctionalitynecessarytomanagethestronglytyped

collection.TheCollectionBaseandDictionaryBaseclassescallthe

appropriatemethodbeforeandaftermodificationsaremadetothe

underlyingcollectionthroughtheListorDictionaryproperties.



2.12StoreaSerializableObjecttoaFile

Problem

Youneedtostoreaserializableobjectanditsstatetoafileandthen

deserializeitlater.



Solution

Useaformattertoserializetheobjectandwriteittoa

System.IO.FileStream.Whenyouneedtoretrievetheobject,usethe

sametypeofformattertoreadtheserializeddatafromthefileand

deserializetheobject.The.NETFrameworkclasslibraryincludesthe

followingformatterimplementationsforserializingobjectstobinaryor

SOAPformat:

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

System.Runtime.Serialization.Formatters.Soap.SoapFormatter



Discussion

UsingtheBinaryFormatterandSoapFormatterclasses,youcanserialize

aninstanceofanytypethat'sdecoratedwiththeattribute

System.SerializableAttribute.TheBinaryFormatterproducesabinary

datastreamrepresentingtheobjectanditsstate,whereasthe

SoapFormatterproducesaSOAPdocument.

BoththeBinaryFormatterandSoapFormatterclassesimplementthe

interfaceSystem.Runtime.Serialization.IFormatter,whichdefinestwo

methods:SerializeandDeserialize.TheSerializemethodtakesa

System.IO.StreamreferenceandaSystem.Objectreferenceas

arguments,serializestheObject,andwritesittotheStream.The

DeserializemethodtakesaStreamreferenceasanargument,readsthe

serializedobjectdatafromtheStream,andreturnsanObjectreference

toadeserializedobject.YoumustcastthereturnedObjectreferenceto

thecorrecttype.



Important TocalltheSerializeandDeserializemethodsofthe

BinaryFormatterclass,yourcodemustbegrantedthe

SerializationFormatterelementofthepermission

System.Security.Permissions.SecurityPermission.

TocalltheSerializeandDeserializemethodsofthe

SoapFormatterclass,yourcodemustbegrantedfulltrust

becausethe

System.Runtime.Serialization.Formatters.Soap.dll

assemblyinwhichtheSoapFormatterclassisdeclared

doesnotallowpartiallytrustedcallers.Refertorecipe

13.1formoreinformationaboutassembliesandpartially

trustedcallers.

TheBinarySerializationExampleclasslistedheredemonstratestheuse

ofaBinaryFormattertoserializeaSystem.Collections.ArrayList

containingalistofpeopletoafile.TheArrayLististhendeserializedfrom

thefileandthecontentsdisplayedtotheconsole.

usingSystem.IO;

usingSystem.Collections;

usingSystem.Runtime.Serialization.Formatters.Binary;

publicclassBinarySerializationExample{

publicstaticvoidMain(){



//CreateandconfiguretheArrayListtoserialize

ArrayListpeople=newArrayList();

people.Add("Graeme");

people.Add("Lin");

people.Add("Andy");

//SerializetheArrayListobject

FileStreamstr=File.Create("people.bin");

BinaryFormatterbf=newBinaryFormatter();

bf.Serialize(str,people);

str.Close();





//DeserializetheArrayListobject

str=File.OpenRead("people.bin");

bf=newBinaryFormatter();

people=(ArrayList)bf.Deserialize(str);

str.Close();



//DisplaythecontentsofthedeserializedArrayListo

foreach(stringsinpeople){



System.Console.WriteLine(s);

}

}

}

YoucanuseaSoapFormatterclassinexactlythesamewayasshownin

theBinarySerializationExampleclass;allyouneedtodoisreplaceeach

instanceofBinaryFormatterwithSoapFormatterandchangetheusing

directivestoimporttheSystem.Runtime.Serialization.Formatters.Soap

namespace.Youmustalsoincludeareferencetothe

System.Runtime.Serialization.Formatters.Soap.dllassemblywhenyou

compilethecode.ThefileSoapSerializationExample.csinthesample

codeforthischaptercontainsanexampleofhowtousethe

SoapFormatterclass.

ToillustratethedifferentresultsachievedusingtheBinaryFormatterand

SoapFormatterclasses,Figure2.1showsthecontentsofthepeople.bin

filegeneratedusingtheBinaryFormatterclass,whereasFigure2.2

showsthecontentsofthepeople.xmlfilegeneratedusingthe

SoapFormatterclass.





Figure2.1:Contentsofthepeople.binfile.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

8 Add, Subtract, and Compare Dates and Times

Tải bản đầy đủ ngay(0 tr)

×