Properties In C#

文章推薦指數: 80 %
投票人數:10人

Property in C# is a member of a class that provides a flexible mechanism for classes to expose private fields. Internally, C# properties are ... PropertiesInC# RajeshVS UpdateddateOct21,2020 1.4m 0 29 LearnhowtousepropertiesinC#. facebook twitter linkedIn Reddit WhatsApp Email Bookmark Print OtherArtcile Expand PropertyinC#isamemberofaclassthatprovidesaflexiblemechanismforclassestoexposeprivatefields.Internally,C#propertiesarespecialmethodscalledaccessors.AC#propertyhavetwoaccessors,getpropertyaccessorandsetpropertyaccessor.Agetaccessorreturnsapropertyvalue,andasetaccessorassignsanewvalue.Thevaluekeywordrepresentsthevalueofaproperty. PropertiesinC#and.NEThavevariousaccesslevelsthatisdefinedbyanaccessmodifier.Propertiescanberead-write,read-only,orwrite-only.Theread-writepropertyimplementsboth,agetandasetaccessor.Awrite-onlypropertyimplementsasetaccessor,butnogetaccessor.Aread-onlypropertyimplementsagetaccessor,butnosetaccessor.  InC#,propertiesarenothingbutanaturalextensionofdatafields.Theyareusuallyknownas'smartfields'inC#community.Weknowthatdataencapsulationandhidingarethetwofundamentalcharacteristicsofanyobjectorientedprogramminglanguage.InC#,dataencapsulationispossiblethrougheitherclassesorstructures.Byusingvariousaccessmodifierslikeprivate,public,protected,internaletcitispossibletocontroltheaccessibilityoftheclassmembers.  Usually,insideaclass,wedeclareadatafieldasprivateandwillprovideasetofpublicSETandGETmethodstoaccessthedatafields.Thisisagoodprogrammingpracticesincethedatafieldsarenotdirectlyaccessibleoutsidetheclass.Wemustusetheset/getmethodstoaccessthedatafields.  Anexample,whichusesasetofset/getmethods,isshownbelow.  //SET/GET methods  //Author: [email protected]  using System;  class MyClass  {      private int x;      public void SetX(int i)      {          x = i;      }      public int GetX()      {          return x;      }  }  class MyClient  {      public static void Main()      {          MyClass mc = new MyClass();          mc.SetX(10);          int xVal = mc.GetX();          Console.WriteLine(xVal);    }  } Theoutputfromabovelistingisshownbelow.        ButC#providesabuiltinmechanismcalledpropertiestodotheabove.InC#,propertiesaredefinedusingthepropertydeclarationsyntax.Thegeneralformofdeclaringapropertyisasfollows.        {        get     {     }        set     {     }  }   Wherecanbeprivate,public,protectedorinternal.ThecanbeanyvalidC#type.Notethatthefirstpartofthesyntaxlooksquitesimilartoafielddeclarationandsecondpartconsistsofagetaccessorandasetaccessor.  Forexample,theaboveprogramcanbemodifiedwithapropertyXasfollows. class MyClass  {      private int x;      public int X      {          get          {              return x;          }          set          {              x = value;          }      }  }   TheobjectoftheclassMyClasscanaccessthepropertyXasfollows. MyClass mc = new MyClass();   mc.X=10;//callssetaccessorofthepropertyX,andpass10asvalueofthestandardfield'value'.  Thisisusedforsettingvalueforthedatamemberx. Console.WriteLine(mc.X);//displays10.CallsthegetaccessorofthepropertyX.  Thecompleteprogramisshownbelow. //C#: Property  //Author: [email protected]  using System;  class MyClass  {      private int x;      public int X      {          get          {              return x;          }          set          {              x = value;          }      }  }  class MyClient  {      public static void Main()      {          MyClass mc = new MyClass();          mc.X = 10;          int xVal = mc.X;          Console.WriteLine(xVal);//Displays 10      }  }   Rememberthatapropertyshouldhaveatleastoneaccessor,eithersetorget.Thesetaccessorhasafreevariableavailableinitcalledvalue,whichgetscreatedautomaticallybythecompiler.Wecan'tdeclareanyvariablewiththenamevalueinsidethesetaccessor. Wecandoverycomplicatedcalculationsinsidethesetorgetaccessor.Eventheycanthrowexceptions.  Sincenormaldatafieldsandpropertiesarestoredinthesamememoryspace,inC#,itisnotpossibletodeclareafieldandpropertywiththesamename.  StaticProperties C#alsosupportsstaticproperties,whichbelongstotheclassratherthantotheobjectsoftheclass.Alltherulesapplicabletoastaticmemberareapplicabletostaticpropertiesalso.  Thefollowingprogramshowsaclasswithastaticproperty. //C# : static Property  //Author: [email protected]  using System;  class MyClass  {      private static int x;      public static int X      {          get          {              return x;          }          set          {              x = value;          }      }  }  class MyClient  {      public static void Main()      {          MyClass.X = 10;          int xVal = MyClass.X;          Console.WriteLine(xVal);//Displays 10      }  }   Rememberthatset/getaccessorofstaticpropertycanaccessonlyotherstaticmembersoftheclass.Also,staticpropertiesareinvokingbyusingtheclassname.   Properties&Inheritance  ThepropertiesofaBaseclasscanbeinheritedtoaDerivedclass. //C# : Property : Inheritance  //Author: [email protected]  using System;  class Base  {      public int X      {          get          {              Console.Write("Base GET");              return 10;          }          set          {              Console.Write("Base SET");          }      }  }  class Derived : Base  {  }  class MyClient  {      public static void Main()      {          Derived d1 = new Derived();          d1.X = 10;          Console.WriteLine(d1.X);    }  } Theoutputfromabovelistingisshownbelow.       Theaboveprogramisverystraightforward.Theinheritanceofpropertiesisjustlikeinheritanceanyothermember.  Properties&Polymorphism  ABaseclasspropertycanbepolymorphicallyoverriddeninaDerivedclass.Butrememberthatthemodifierslikevirtual,overrideetcareusingatpropertylevel,notataccessorlevel. //C# : Property : Polymorphism  //Author: [email protected]  using System;  class Base  {      public virtual int X      {          get          {              Console.Write("Base GET");              return 10;          }          set          {              Console.Write("Base SET");          }      }  }  class Derived : Base  {      public override int X      {          get          {              Console.Write("Derived GET");              return 10;          }          set          {              Console.Write("Derived SET");          }      }  }  class MyClient  {      public static void Main()      {          Base b1 = new Derived();          b1.X = 10;          Console.WriteLine(b1.X);    }  } Theoutputfromabovelistingisshownbelow.       AbstractProperties  Apropertyinsideaclasscanbedeclaredasabstractbyusingthekeywordabstract.Rememberthatanabstractpropertyinaclasscarriesnocodeatall.Theget/setaccessorsaresimplyrepresentedwithasemicolon.Inthederivedclasswemustimplementbothsetandgetassessors.  Iftheabstractclasscontainsonlysetaccessor,wecanimplementonlysetinthederivedclass.  Thefollowingprogramshowsanabstractpropertyinaction. //C# : Property : Abstract  //Author: [email protected]  using System;  abstract class Abstract  {      public abstract int X      {          get;          set;      }  }  class Concrete : Abstract  {      public override int X      {          get          {              Console.Write(" GET");              return 10;          }          set          {              Console.Write(" SET");          }      }  }  class MyClient  {      public static void Main()      {          Concrete c1 = new Concrete();          c1.X = 10;          Console.WriteLine(c1.X);    }  }   Theoutputfromabovelistingisshownbelow.       ThepropertiesareimportantfeaturesaddedinlanguagelevelinsideC#.TheyareveryusefulinGUIprogramming.RememberthatthecompileractuallygeneratestheappropriategetterandsettermethodswhenitparsestheC#propertysyntax.   PropertiesAccessModifiers   Accessmodifiersdefinestheaccesslevelofapropertywhetherapropertycanbeaccessedbyanycallerprogram,withinanassembly,orjustwithinaclass.   Thefollowingtabledescribesaccesslevelmodifiers.  public-Thetypeormembercanbeaccessedbyanyothercodeinthesameassemblyoranotherassemblythatreferencesit.Private-Thetypeormembercanbeaccessedonlybycodeinthesameclassorstruct.protected-Thetypeormembercanbeaccessedonlybycodeinthesameclass,orinaclassthatisderivedfromthatclass.internal-Thetypeormembercanbeaccessedbyanycodeinthesameassembly,butnotfromanotherassembly.protectedinternal-Thetypeormembercanbeaccessedbyanycodeintheassemblyinwhichitisdeclared,orfromwithinaderivedclassinanotherassembly.privateprotected-Thetypeormembercanbeaccessedonlywithinitsdeclaringassembly,bycodeinthesameclassorinatypethatisderivedfromthatclass. AutomaticallyImplementedProperties   AtypicalimplementationofapublicpropertylookslikeListing.Thedefaultimplementationofapropertyneedsagetterandsetter. private string name;  public string Name  {     get { return this.name; }     set { this.name = value; }  }   Auto-implementedpropertiesinC#makescodemorereadableandcleanifthereisnoadditionalcalculationneeded.TheabovecodeofListingcanbereplacedbythefollowingonelineofcodeinListing public string Name { get; set; }   Incaseofauto-implementedproperties,thecompilercreatesaprivatefieldvariablethatcanonlybeaccessedthroughtheproperty'sgetterandsetter.   CodelistedinListingisaclasswithseveralauto-initializedproperties. using System;  class Author {      // Read-write properties        public string Name {          get;          set;      }      public string Publisher {          get;          set;      }      public string Book {          get;          set;      }      public Int16 Year {          get;          set;      }      public double Price {          get;          set;      }      public string PriceInString {          get {              return string.Format("${0}", Price);          }      }      // Read-only properties        public string Names {          get;      }      // Initialization of a property        public double AuthorCount {          get;          private set;      } = 99;      // Class constructor        public Author(string name, string publisher, string book, Int16 year, double price) {          Name = name;          Publisher = publisher;          Book = book;          Year = year;          Price = price;      }      // Public methods        public string AuthorDetails() {          return string.Format("{0} is an author of {1} published by {2} in year {3}. Price: ${4}", Name, Book, Publisher, Year, Price);      }      public double CostOfThousandBooks() {          if (Price > 0) return Price * 1000;          return 0;      }  }  ThecodeinListingiscreatesaninstanceoftheclassandcallsitsmethodsandproperties. class Program   {      static void Main()     {          Author author = new Author("Mahesh Chand", "Apress", "Programming C#", 2003, 49.95);          Console.WriteLine(author.AuthorDetails());          Console.WriteLine("Author published his book in {0}", author.Year);          author.Price = 50;          Console.WriteLine(author.CostOfThousandBooks().ToString());          Console.ReadKey();      }  }   AbstractPropertiesC#propertiesPropertiesinC#StaticProperties NextRecommendedReading FEATUREDARTICLES ViewAll TRENDINGUP 01HowLazyloadingInBlazorCanIncreaseYourApplicationPerformance!02EverythingYouNeedToKnowAboutAzureDataLake⌛03CleanArchitectureWith.NET604Angular13LatestFeatures05EasilyCreateSPAWith.NET6.0AndAngular13AndDeployToAzure06GettingStartedWith.NET7.007HowToMeasureCentralTendencyUsingPandasInPython-DataScience08ImplementSwaggerUIInASP.NETWebAPIRestfulServiceForDocumentationUsingSwashbuckle09SevenMinutesToaBetterSellingPodcastEp.1610HowToAddDynamicControlsWithReactiveFormsValidationsInAngular ViewAll



請為這篇文章評分?