开发者

What's the best approach for readonly property

开发者 https://www.devze.com 2022-12-22 15:23 出处:网络
I\'m us开发者_JAVA技巧ing a model UserRepository->User The Repository is used to Save and Load the User.

I'm us开发者_JAVA技巧ing a model UserRepository->User

The Repository is used to Save and Load the User.

I want to be able to set the ID in the Repository, but I don't want it to be access by UI.

The User and Repository are found in a Core project, and the UI in a Web.

Is there a way to do this, like a modifier for the property, or should I put the ID in the User contructor ?

Thanks


You can use a property without a setter and a private variable like this:

private int _id; //Set locally
public int ID
{
  get { return _id; }
}
//in the class _id = 5;

Or use automatic properties with a private setter like this:

public int ID { get; private set; }
//in the class ID = 5; this won't work outside the class

In the second/automatic case, it's really just the compiler doing the first example, just a bit quicker and easier on the eyes.


I have used this patten (not familiar with C# as such, but the idea should work):

class Foo
{
    protected int id;

    public int GetID()
    {
        return (ID);
    }
}

class MutableFoo : Foo
{
    public void SetID(int val)
    {
        id = val;
    }
}

then the UI only deals with the "Foo" class which is read-only while other parts can deal with the "MutableFoo" which is read/write. You should be able to only ever create instances of "MutableFoo" and then pass them to other parts of the code that receives then as "Foo", this the UI code would have read-only access to the objects while other parts can have read-write access.

I'd probably make "Foo" abstract as well (I cannot think of a case where I haven't).

0

精彩评论

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

关注公众号