我正在使用模型 UserRepository->User
存储库用于保存和加载用户。
我希望能够在存储库中设置 ID,但我不希望通过 UI 访问它。
User 和 Repository 位于 Core 项目中,UI 位于 Web 中。
有没有办法做到这一点,比如属性的修饰符,或者我应该把 ID 放在用户构造函数中吗?
谢谢
最佳答案
您可以像这样使用不带 setter 的属性和私有(private)变量:
private int _id; //Set locally
public int ID
{
get { return _id; }
}
//in the class _id = 5;
或者像这样使用带有私有(private) setter 的自动属性:
public int ID { get; private set; }
//in the class ID = 5; this won't work outside the class
在第二种/自动情况下,实际上只是编译器在执行第一个示例,只是速度更快,看起来更轻松。
关于c# - 只读属性的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2435332/