c# - 只读属性的最佳方法是什么

标签 c# properties

我正在使用模型 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/

相关文章:

delphi - 设置Label和StaticText Color属性问题-Delphi 2009

qt - 使用 QDBusInterface 获取 DBus Interface 属性时出错

css - getComputedStyle 返回 CSSStyleDeclaration 但访问时所有属性均为空

ios - 在 Swift 3.1 中使用自定义 Setter 更新数组属性

java - 如何在servlet中使用属性键值

c# - System.PlatformNotSupportedException : Speech Recognition is not available on this system. 找不到 SAPI 和语音识别引擎

c# - 将域模型类型转换为 ViewModel

c# - 起订量框架的真正目的

c# - 从 XML 数据反序列化数组(在 ServiceStack 中)

c# - 无法在 .Net Core 3.1 中的 Web Api 中使用 Cors