开发者

How do restrict access to a class property to only within the same namespace

How do restrict 开发者_运维知识库access to a class property to within the same namespace? Consider the following class. The Content class cannot Publish itself, instead the ContentService class will do a few things before changing the state to published.

public class Content : Entity, IContent
    {
        public string Introduction { get; set; }

        public string Body { get; set; }

        public IList<Comment> Comments { get; set; }

        public IList<Image> Images { get; private set; }

        public State Status { get; } 
    }

public class ContentService
    {
        public IContent Publish(IContent article)
        {
            //Perform some biz rules before publishing   
            article.Status = State.Published;
            return article;
        }
    }

How can i make it so only the ContentService class can change the state of the article?

Are there any deisng patterns to help me deal with this?


You can use the "internal" access modifier so that only classes within the same Assembly can modify the Content class's State member (but everyone even in other assemblies can GET the value).

public State Status { get; internal set; } 

So now ContentService can set the state because it is in the same Assembly, but outside callers can only get the state (they're not allowed to set it).


Java has the notion of "package visible" or "package private". This is in fact the default for anything where you don't specify a visibility (private or public). For some reason, almost no one ever uses this.


Declare ContentService as a friend?

Alternatively, Java has an access modifier that amounts to "package-private".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜