Looking for a short & simple example of getters/setters in C#

后端 未结 12 431
悲哀的现实
悲哀的现实 2020-12-07 12:35

I am having trouble understanding the concept of getters and setters in the C# language. In languages like Objective-C, they seem an integral part of the system, bu

相关标签:
12条回答
  • 2020-12-07 12:39

    My explanation would be following. (It's not so short, but it's quite simple.)


    Imagine a class with a variable:

    class Something
    {
        int weight;
        // and other methods, of course, not shown here
    }
    

    Well, there is a small problem with this class: no one can see the weight. We could make weight public, but then everyone would be able to change the weight at any moment (which is perhaps not what we want). So, well, we can do a function:

    class Something
    {
        int weight;
        public int GetWeight() { return weight; }
        // and other methods
    }
    

    This is already better, but now everyone instead of plain something.Weight has to type something.GetWeight(), which is, well, ugly.

    With properties, we can do the same, but the code stays clean:

    class Something
    {
        public int weight { get; private set; }
        // and other methods
    }
    
    int w = something.weight // works!
    something.weight = x; // doesn't even compile
    

    Nice, so with the properties we have finer control over the variable access.

    Another problem: okay, we want the outer code to be able to set weight, but we'd like to control its value, and not allow the weights lower than 100. Moreover, there are is some other inner variable density, which depends on weight, so we'd want to recalculate the density as soon as the weight changes.

    This is traditionally achieved in the following way:

    class Something
    {
        int weight;
        public int SetWeight(int w)
        {
            if (w < 100)
                throw new ArgumentException("weight too small");
            weight = w;
            RecalculateDensity();
        }
        // and other methods
    }
    
    something.SetWeight(anotherSomething.GetWeight() + 1);
    

    But again, we don't want expose to our clients that setting the weight is a complicated operation, it's semantically nothing but assigning a new weight. So the code with a setter looks the same way, but nicer:

    class Something
    {
        private int _w;
        public int Weight
        {
            get { return _w; }
            set
            {
                if (value < 100)
                    throw new ArgumentException("weight too small");
                _w = value;
                RecalculateDensity();
            }
        }
        // and other methods
    }
    
    something.Weight = otherSomething.Weight + 1; // much cleaner, right?
    

    So, no doubt, properties are "just" a syntactic sugar. But it makes the client's code be better. Interestingly, the need for property-like things arises very often, you can check how often you find the functions like GetXXX() and SetXXX() in the other languages.

    0 讨论(0)
  • 2020-12-07 12:41

    This is a basic example of an object "Article" with getters and setters:

      public class Article
        {
    
            public String title;
            public String link;
            public String description;
    
            public string getTitle()
            {
                return title;
            }
    
            public void setTitle(string value)
            {
                title = value;
            }
    
            public string getLink()
            {
                return link;
            }
    
            public void setLink(string value)
            {
                link = value;
            }
            public string getDescription()
            {
                return description;
            }
    
            public void setDescription(string value)
            {
                description = value;
            }
        }
    
    0 讨论(0)
  • 2020-12-07 12:42

    As far as I understand getters and setters are to improve encapsulation. There is nothing complex about them in C#.

    You define a property of on object like this:

    int m_colorValue = 0;
    public int Color 
    {
       set { m_colorValue = value; }
       get { return m_colorValue; }
    }
    

    This is the most simple use. It basically sets an internal variable or retrieves its value. You use a Property like this:

    someObject.Color = 222; // sets a color 222
    int color = someObject.Color // gets the color of the object
    

    You could eventually do some processing on the value in the setters or getters like this:

    public int Color 
    {
       set { m_colorValue = value + 5; }
       get { return m_colorValue  - 30; }
    }
    

    if you skip set or get, your property will be read or write only. That's how I understand the stuff.

    0 讨论(0)
  • 2020-12-07 12:43

    Simple example

        public  class Simple
        {
            public int Propery { get; set; }
        }
    
    0 讨论(0)
  • 2020-12-07 12:44

    Internally, getters and setters are just methods. When C# compiles, it generates methods for your getters and setters like this, for example:

    public int get_MyProperty() { ... }
    public void set_MyProperty(int value) { ... }
    

    C# allows you to declare these methods using a short-hand syntax. The line below will be compiled into the methods above when you build your application.

    public int MyProperty { get; set; }
    

    or

    private int myProperty;
    public int MyProperty 
    { 
        get { return myProperty; }
        set { myProperty = value; } // value is an implicit parameter containing the value being assigned to the property.
    }
    
    0 讨论(0)
  • 2020-12-07 12:46

    well here is common usage of getter setter in actual use case,

    public class OrderItem 
    {
    public int Id {get;set;}
    public int quantity {get;set;}
    public int Price {get;set;}
    public int TotalAmount {get {return this.quantity *this.Price;}set;}
    }
    
    0 讨论(0)
提交回复
热议问题