C# Property Examples - Dot Net Perls
文章推薦指數: 80 %
Make properties with the get and set keywords. Understand that properties are used for data access.
HomeSearchC#PropertyExamplesMakepropertieswiththegetandsetkeywords.Understandthatpropertiesareusedfordataaccess.Property.Considerthephysicalcomputeryouareusing.Ithasmanyproperties—asize,aweight,adateitwasbuilt.Propertiesdescribethiscomputer.Propertyuse.InC#,weusepropertiesonaclass(likeaComputerclass)todescribetheclass.Theycanbesetandreadfromlikeotherfields,andspecialcodecanberun.Simpleexample.Tostart,weintroduceanExampleclass.Onefield,aninteger,ispresent—itisusedasabackingstorefortheNumberproperty.NumberThisisanintpropertyintheExampleclass.Numberprovidesgetandsetimplementations.GetThegetimplementationmustincludeareturnstatement.Itcanaccessanymemberontheclass.SetThesetimplementationreceivestheimplicitargument"value."Thisisthevaluetowhichthepropertyisassigned.ValueC#programthatusespublicintpropertyusingSystem;
classExample
{
int_number;
publicintNumber
{
get
{
returnthis._number;
}
set
{
this._number=value;
}
}
}
classProgram
{
staticvoidMain()
{
Exampleexample=newExample();
example.Number=5;//set{}
Console.WriteLine(example.Number);//get{}
}
}5Automaticproperty.WeseeautomaticallyimplementedpropertysyntaxinC#.Ahiddenfieldisgenerated—thenthegetandsetstatementsareexpandedtousethathiddenfield.ExpressionThe*=operatorisusedtomultiplythepropertybyitself.Becausepropertiesaremeanttolooklikefields,thisisallowed.C#programthatusesautomaticallyimplementedpropertyusingSystem;
classExample
{
publicintNumber
{
get;
set;
}
}
classProgram
{
staticvoidMain()
{
Exampleexample=newExample();
example.Number=8;
example.Number*=4;
Console.WriteLine(example.Number);
}
}32Enum.ThisexampleshowstheDayOfWeekenumtypeinaproperty.Wealsoinsertcodeinthegetter(orsetter)thatchecksthebackingstoreortheparametervalue.EnumDayOfWeekTypesLikeamethod,apropertycanactonanytype,evenenumtypeslikeDayOfWeek.Manypropertieswillusestringorint.C#programthatusesenumpropertyusingSystem;
classExample
{
DayOfWeek_day;
publicDayOfWeekDay
{
get
{
//Wedon'tallowthistobeusedonFriday.
if(this._day==DayOfWeek.Friday)
{
thrownewException("Invalidaccess");
}
returnthis._day;
}
set
{
this._day=value;
}
}
}
classProgram
{
staticvoidMain()
{
Exampleexample=newExample();
example.Day=DayOfWeek.Monday;
Console.WriteLine(example.Day==DayOfWeek.Monday);
}
}TruePrivate.Wemakeaprivateproperty.HeretheIsFoundpropertycanonlybesetintheExampleclass.WesetitintheExampleconstructor.ThenWecanonlygetthepropertyintheProgram.MainmethodbyusinganExampleinstance.C#programthatusesprivatesetterinpropertyusingSystem;
classExample
{
publicExample()
{
//Settheprivateproperty.
this.IsFound=true;
}
bool_found;
publicboolIsFound
{
get
{
returnthis._found;
}
privateset
{
//Canonlybecalledinthisclass.
this._found=value;
}
}
}
classProgram
{
staticvoidMain()
{
Exampleexample=newExample();
Console.WriteLine(example.IsFound);
}
}TrueEntireproperty.Wecanalsomakeanentirepropertyprivate.Ifwedothis,wecanonlyusethepropertyinthesameenclosingclass.PrivateTheDisplaymethodintheexampleshowshowtousetheprivateproperty.NoteThissyntaxislessusefulinmostprograms.Butitexists,andmaybehelpfulinacomplexclass.ClassC#programthatusesprivatepropertyusingSystem;
classExample
{
int_id;
privateintId
{
get
{
returnthis._id;
}
set
{
this._id=value;
}
}
publicvoidDisplay()
{
//Accesstheprivatepropertyinthismethod.
this.Id=7;
Console.WriteLine(this.Id);
}
}
classProgram
{
staticvoidMain()
{
Exampleexample=newExample();
example.Display();
}
}7Static.Propertiescanalsobestatic—thismeanstheyareassociatedwiththetypeandnotaninstance.Staticclassescanonlyhavestaticproperties.StaticCountThispropertyhasasideeffect.Itcausesthefieldtobeincrementeduponeachaccess.WarningSideeffectsarenotusuallyagooddesignfeatureinprograms.Theycanmakethelogichardtofollow.SetterThisisomitted.Thismakessenseforapropertythatcomputesavalueentirelyinmemory,orbasedonotherfieldsorproperties.C#programthatusesstaticpropertyusingSystem;
classExample
{
staticint_count;
publicstaticintCount
{
get
{
//Sideeffectofthisproperty.
_count++;
return_count;
}
}
}
classProgram
{
staticvoidMain()
{
Console.WriteLine(Example.Count);
Console.WriteLine(Example.Count);
Console.WriteLine(Example.Count);
}
}1
2
3Automatic,private.Letusconsiderhowtomakegettersorsettersonanautomaticproperty.Wecannotomiteitherthegetterorsetterinthiskindofproperty.NoteTheerrorreportedbytheC#compilerreads:"Automaticallyimplementedpropertiesmustdefinebothgetandsetaccessors."C#programthatusesprivatesetter,autopropertyusingSystem;
classExample
{
publicExample()
{
//Useprivatesetterintheconstructor.
this.Id=newRandom().Next();
}
publicintId
{
get;
privateset;
}
}
classProgram
{
staticvoidMain()
{
Exampleexample=newExample();
Console.WriteLine(example.Id);
}
}2077325073Automatic,defaultvalues.Automaticpropertieshavesupportfordefaultvaluesmuchlikefields.HereweassigntheQuantitypropertyofMedicationto30bydefault.C#programthatusesdefaultvalueusingSystem;
classMedication
{
publicintQuantity{get;set;}=30;//Hasdefaultvalue.
}
classProgram
{
staticvoidMain()
{
Medicationmed=newMedication();
//Thequantityisbydefault30.
Console.WriteLine(med.Quantity);
//Wecanchangethequantity.
med.Quantity*=2;
Console.WriteLine(med.Quantity);
}
}30
60Expression-bodiedproperties.Wecanuselambda-stylesyntaxtospecifyproperties.Theseareexpression-bodiedproperties—weuse"get"and"set"andthentheresultontherightside.C#programthatusesexpression-bodiedpropertiesclassProgram
{
privatestaticinttest;
publicstaticintTest{get=>test;set=>test=value;}
staticvoidMain()
{
//Usetheproperty.
Program.Test=200;
System.Console.WriteLine(Program.Test);
}
}200Benchmark,properties.Compileroptimizationsensurethatpropertiesareefficient.Thesesameoptimizationsareusedonmethods,whichsharetheunderlyingimplementationwithproperties.Version1Thiscodeusesaproperty.Itsetsaproperty,andthengetsthevalueoftheproperty.Version2Thisversionofthecodeusesafielddirectly.Itperformsthesamelogicalstepsthatversion1does.ResultTherewasnodifferenceinperformancewiththepropertyandthefield.Itisapparentthepropertyaccessisinlined.TipTheJITcompilercaninlinepropertiesthatdon'thavelogicinsideofthem.Sotheyareasefficientasfields.C#programthatbenchmarkspropertiesusingSystem;
usingSystem.Diagnostics;
classProgram
{
staticstring_backing;//Backingstoreforproperty.
staticstringProperty//Getterandsetter.
{
get
{
return_backing;
}
set
{
_backing=value;
}
}
staticstringField;//Staticfield.
staticvoidMain()
{
constintm=100000000;
for(intx=0;x<10;x++)//Tentests.
{
Stopwatchs1=newStopwatch();
s1.Start();
//Version1:testproperty.
for(inti=0;i
延伸文章資訊
- 1Learn C# Properties: Getters and Setters at ... - Codeasy
"To create a property, use the same syntax as for fields, but add a get; to generate a getter and...
- 2C# Get Set Modifier
- 3C# Properties (Get and Set) - W3Schools
Example explained. The Name property is associated with the name field. It is a good practice to ...
- 4C# Property Examples - Dot Net Perls
Make properties with the get and set keywords. Understand that properties are used for data access.
- 5What is the { get; set; } syntax in C#? - Stack Overflow
It's basically a shorthand way of creating properties for a class in C#, without having to define...