简体   繁体   中英

c# Choosing Between Properties and Methods

After reading this microsoft article about when to use properties and methods, I'm a little bit confused.

At the example at the bottom they say:

The following code example shows a complete application that assumes that a property access is computationally inexpensive. The EmployeeData class incorrectly defines a property that returns a copy of an array.

specifically

The EmployeeData class incorrectly defines a property that returns a copy of an array.

What would be the right way to do it?

fiddle of the example code

This is just a guideline, but your properties should be as lightweight as possible. Copying an array, just like in the example, is quite expansive for a property. It should be a method. This way, anyone using this code knows it could take a bit of time. Properties usually reflect accessors for private fields, so people expect it to return almost immediately. Hope this makes sense.

The property is "incorrect" because the code inside it is slow.

public EmployeeRecord[] Employees
{
    get 
    {
        return CopyEmployeeRecords();   // slow code in property - bad
    }
}

Instead, write a method:

public EmployeeRecord[] Employees()
{
    return CopyEmployeeRecords();       // slow code in method - ok
}

The section

use a method, rather than a property, in the following situations.

in the article you were reading tells you to use a method instead of a property of the property returns an array.

So the right way to do this would be creating a method to copy the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM