Property visibility in abstract class

老子叫甜甜 提交于 2020-01-24 11:54:54

问题


Does someone knows C# best practice about the way to define attribute visibility (private or protected) behind public property in abstract class or parent class.

In other worlds what is the best practice by default (and why) between:

public abstract class MyClass
{
    private string myAttribute;

    public string MyAttribute
    {
        get { return myAttribute; }
        set { myAttribute = value; }
    }
}

and

public abstract class MyClass
{
    protected string myAttribute;

    public string MyAttribute
    {
        get { return myAttribute; }
        set { myAttribute = value; }
    }
}

I think children class should have the way to handle directly this protected attribute but it may not be a good practice if getter or setter contains more code...

What do you think about that?

Thank you.


回答1:


Non-const fields should be really always private. If you need to use a field because you cannot use auto-properties for some reason, make sure it's private. Children classes should access it via public or protected properties.




回答2:


Definitely private. However, there's an easier way to do what you're doing:

public abstract class MyClass
{
    public string MyAttribute { get; set; }
}

This does exactly the same thing, but its a lot easier to maintain.




回答3:


Definitely private. When defining an abstract class I only make items protected if it is a behavior that meets the following

  1. Sub classes must override or have access to
  2. External classes should not have access to

In this case you've already given external classes access to the value. Making it protected doesn't give the sub-class any real advantage.




回答4:


I found one limitation for public get, protected set: comments. Because comments should not be the same for public and protected, respecting stylecop: - Comment for public: Gets comment - Comment for protected: Gets or sets comment

I don't want to do 2 properties for both visibility, so i resolved it quiclky with the following comment: Gets ot set (protected) comment.

If you have better practice, it's welcome.



来源:https://stackoverflow.com/questions/2148132/property-visibility-in-abstract-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!