简体   繁体   中英

Is there any reason not to use 'protected' properties?

Just wondering...

Is there any reasons not to use protected properties?

I mean instead of using this:

public abstract class Foo
{
    protected Bar { get; private set; }
}

to use this one:

public abstract class Foo
{
    private Bar _bar;

    protected Foo(Bar bar)
    {
        _bar = bar;
    }

    protected GetBar()
    {
        return _bar;
    }
}

I don't see any reason why you would use a GetXXX() method instead of a property regardless of it's modifiers.

Since you tagged this question with C# tag, I strictly recommend using the first approach. That is what properties are for.

Use a method only when value returned by it can be different every time you call it regardless of it's state. For example, DateTime.Now was a mistake and should have been a method.

For more details refer to Property Usage Guidelines on MSDN . On a side note, it's surprising how they haven't had a need to change it since Framework 1.1 .

A few more reasons to use properties instead of methods:

  • Data binding can only see properties
  • You can use read only or write only semantics.

仅当您在类中具有不可写或不可读的属性时

The question is not really about protected it has more with: why should I use properties?

Propeties are logically equivalent with Getter/Setter method pairs, whatever you can do with a with a Name {get{} \\ set{}} you can do with a GetName() \\ SetName() pair and vice versa, especially as C# has getter and setter accessors, so we can play with the accessibility too.

But, there are some folks that feel that public (or protected) properties are a bit like cheating from an OOP perspective, especially if all that the property does is just expose a backing field. After all person.Name = "SWeko" seems like it changes the state of the object externally, while person.SetName("SWeko") merely tells the object that it needs to change it's state. And from a purely theoretic standpoint I think that those objections have merit.

However, not all of us have the luxury of living in ivory towers, so the concept of properties is really usefull, as it's more readable, less error prone, and IMHO, closer to the real world model. It also provides us with a kind of dichotomy, when i write something like this:

person.Name = "SWeko";
person.Work();

I expect that the first line will a fast assignment, and will not have side-effects, while I expect that the second line will do something more, and probably affect the inner state of the object. When I use Getter and Setter method, no such distiction is immediately obvious:

person.SetName("SWeko");
person.Work();

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