30/09/2018, 22:17

Hỏi về get, set trong C#

Chào mọi người mình xin hỏi 1 chút là khi đã dùng private thì có set, get. thế sao đoạn code dưới đây đã có public rồi sao còn dùng set, get làm gì nữa ạ

public class Book 
    {
        public string ISBN { set; get; }
        public string Title { set; get; }
        public string Author { set; get; }   
        public DateTime PublishDate { set; get; }
        public string ShowBook()
        {
            return ISBN + " - " + Title + " - " + Author + " - " + PublishDate ; 
        }
BigCat viết 00:18 ngày 01/10/2018

In C# we have Properties that provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field.

Why we use properties instead fields in C#
Just for encapsulation principle. For hinding concrete implementaiton, and plus, you have an opportunity (in this case) to add additional code inside get/set.

https://blogs.msdn.microsoft.com/vbteam/2009/09/04/properties-vs-fields-why-does-it-matter-jonathan-aneja/

public string ISBN { set; get; }
      //decare variable (field)
        private string title; 
        private string Author ; 
        private string PublishDate ; 

       /// Declare a Code properties
        public string Title {
             set{ title = value;} 

             get{ return title; }
        }
        public string Author { set; get; }   

        public DateTime PublishDate { set; get; }

        public string ShowBook()
        {
            return ISBN + " - " + Title + " - " + Author + " - " + PublishDate ; 
        }
Bài liên quan
0