Why we need Properties in C#

前端 未结 8 1203
萌比男神i
萌比男神i 2020-12-01 09:31

Can you tell me what is the exact usage of properties in C# i mean practical explanation

in our project we are using properties like

/// 

        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 10:33

    That's the way to use it, except for the way you're setting it, possibly. Instead of accessing the member variable, you may want to use the property from within the class, so you can use uniform rules regarding each member variable. This is the primary advantage to using properties, is to bring the access and setter logic all into one place. It really depends on your specific needs whether or not you want to set it using the Property or not. Note though, that in the constructor you want to be very careful when calling the Property, as you may or may not be relying on other parts of the class being initialized which would not be done yet if accessed through the constructor. Again, this depends on your specific implementation.

    It is also a little cleaner to use:

    myObject.Property1 = "Test String";
    Console.WriteLine(myObject.Property1);
    

    Than what you see in some other languages:

    myObject.setProperty1("Test String");
    System.out.writeln(myObject.getProperty1());
    

    Here's a case where you can encapsulate some logic:

    public int Order
    {
        get { return m_order; }
        set
        {
            // Put some rules checking here. Maybe a call to make sure that the order isn't duplicated or some other error based on your business rules.
            m_order = value;
        }
    }
    

    Another way they're useful would be like this:

    public int Order { get; private set; }
    

    And now you've got an auto-implemented property with backing member variable that can only be set inside the class but read everywhere else.

    Finally, if you need to control the logic, you can write this:

    public int Order
    {
        get { return m_order; }
        protected set
        {
            // Again, you can do some checking here if you want...
            m_order = value;
            // You can also do other updates if necessary. Perhaps a database update...
        }
    }
    

提交回复
热议问题