Why we need Properties in C#

2020-01-28 04:57发布

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

/// <summary>
/// column order
/// </summary>
protected int m_order;

/// <summary>
/// Get/Set column order
/// </summary>
public int Order
{
   get { return m_order; }
   set { m_order = value; }
}

/// <summary>
/// constructor
/// </summary>
/// <param name="name">column name</param>
/// <param name="width">column width</param>
/// <param name="order">column order</param>
public ViewColumn(string name, int width, int order)
{
   //
   // TODO: Add constructor logic here
   //
   m_name = name;
   m_width = width;
   m_order = order;
}  


/// <summary>
/// returns the column name, width, and order in list view.
/// </summary>
/// <returns>string represent of the ViewColumn object</returns>
public override string ToString()
{
  return (string.Format("column name = {0}, width = {1}, order = {2}.", 
        m_name, m_width, m_order));
}

/// <summary>
/// Do a comparison of 2 ViewColumn object to see if they're identical.
/// </summary>
/// <param name="vc">ViewColumn object for comparison</param>
/// <returns>True if the objects are identical, False otherwise.</returns>
public override bool Equals(object obj)
{
   ViewColumn vc = (ViewColumn)obj;
   if(m_name == vc.Name &&
        m_width == vc.Width &&
        m_order == vc.Order)
      return true;
   else
      return false;
}

8条回答
冷血范
2楼-- · 2020-01-28 05:34

Design Time Benefits

Properties makes visual designing easy, you have Most Famous Property Browser of Visual Studio to allow you to change properties of object.

Properties also provide additional metadata of validation, visual appearance inside Property Browser, like drop down, range, color picker etc.

Seperate Data and Actions

They truely represent difference between "Data" of object and "Actions" (Methods) of object.

When we look at class, if we have 50 methods to look at, not everyone will always use correct naming of functions, that will make things difficult to understand later on. I always tell the programmers that whenever you program, write the code in such a way that after 5 years, if someone else looks at the code, he should understand the code.

Using method names of data access and some actions create confusion in long run... like in case of Stack, Push/Pop are actions but "Size" or "Count" is data.

Creating property of "Count" simply distinguishes its purpose as data instead of action.

Databinding

As mentioned by others, properties offer advanced level of databinding like two way binding etc.

Access Restrictions

You can have readonly properties and additional accessors as mentioned by others.

Reflection

Its little easy to work with properties in case of writing generic code based on reflection.

Different Storage Implementation

Public variables store data only as members, where else properties provide various ways to store data in different forms like internaly they can be stored as hashtable (as they are done in dependency objects in WPF). They can be cached. They cab be relayed further to some other child entities or foriegn entities. However implementation is hidden for callers.

Validation

Setting property may require certain validation, and validation code in "Set" part of code can easily help you validate the input and report errors accordingly.

Notifications

Set part of method can raise notification events such as INotifyPropertyChanged.PropertyChanged which other objects can listen for and update the display value. This is important part of advanced data binding.

In short, its a new "Standard" of data storage that has advanced facilities then just mere storing the data in the members of class. By avoiding properties typically you can perform all functions, but since implementation may differ from person to person, its a standard which helps everyone to define/access/validate/notify the data storage in one single form called "Properties"

查看更多
ら.Afraid
3楼-- · 2020-01-28 05:34

As Justin noted, Encapsulation is one of the basic tenets of OOP. You would want to keep the internal representation of the data in your class hidden from outside and provide approved ways of viewing/manipulating it.

C# properties are constructs that provide an easy way to do that. In your example, you aren't doing anything inside the get and set methods but in real life you may need to do certain things like

  • Store currency in 10th of cents as a long integer but return to the outside world as a string with 2 decimal spaces and a $ sign.
  • Restrict a certain property to be read-only (or even write-only: for ex:, a password validator/hash generator class).
  • Change the state of the object somehow when this value is set/get.

In Java, you write getters and setters which are plain-old methods that return or accept a value respectively.

查看更多
家丑人穷心不美
4楼-- · 2020-01-28 05:44

Properties are used to restrict direct access to member variables of a class. Abstraction is maintained using properties. Whenever you want to instantiate an object and set data to it's member variables using property you can check some conditions whether the value will be set to the member variable or not. You can restrict read write to a property so that the value of member variable can be readonly, writeonly while accessing the object of that class.

查看更多
成全新的幸福
5楼-- · 2020-01-28 05:48

Here's a common pattern:

class Foo {

    private Bar _bar;

    //here, Foo has a Bar object.  If that object has already been instantiated, return that value.  Otherwise, get it from the database.
    public Bar bar {
        set { _bar = value;}
        get {
            if (_bar == null) {
                _bar = Bar.find_by_foo_name(this._name);
            }
            return _bar;
        }
    }
}

In short, this allows us to access the Bar object on our instance of Foo. This encapsulation means we don't have to worry about how Bar is retrieved, or if foo.bar has already been instantiated. We can just use the object and let the internals of the Foo class take care of it.

查看更多
手持菜刀,她持情操
6楼-- · 2020-01-28 05:52

Lots of reasons:

  • Semantics. Properties separate the implementation of your type from the interface.
  • Binary Compatibility. If you ever need to change a property, you can do so without breaking binary compatibility for dependent code. With fields, you have to recompile everything even if the new implementation uses a property with the same name.
  • Databinding. You can't databind to a field.
查看更多
疯言疯语
7楼-- · 2020-01-28 05:54

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...
    }
}
查看更多
登录 后发表回答