c# - 在不实例化类的情况下访问字段
问题描述
假设我有这样的课程:
public class Offer1
{
private readonly Guid _id = new Guid("7E60g693-BFF5-I011-A485-80E43EG0C692");
private readonly string _description = "Offer1";
private readonly int _minWage = 50000;
//Methods here
}
假设我想在不创建类实例的情况下访问 id。在正常情况下;我只是将字段设为静态并执行此操作:
Offer1.ID //After changing the visibility to public and the name of the field to: ID
但是,我正在尝试遵循 DDD 和 TDD,并且我相信由于明显的原因(例如可测试性)而对此不赞成。我该如何处理?
1) Store the ID in the configuration file and pass it to Offer1 in the constructor. I believe this is a bad idea because it is domain information and should be in the domain model.
2) Use a static field as described above.
3) Something else
这更像是一个设计问题。
解决方案
我建议您使用一个静态字段来保存Guid
,如果每个实例都Offer1
需要一个字段或属性来让 id引用该静态字段Guid
,例如
public class Offer1
{
internal static readonly Guid ID = new Guid(...);
private Guid _id => ID;
// or
private readonly Guid _id = ID;
}
属性变体的优点是并非每个实例都需要内存来存储Guid
. 由于Guid
是一个值类型,每个实例都会为该 guid 分配一个字段。
推荐阅读
- python - 如何将列表作为值附加到数据框的特定列,其中所有其他列都将其值作为常量
- css - CSS 何时使用 ::before/::after 与真实元素
- html - 为什么使用 flex wrap 会破坏包含大图像的项目的高度?
- sed - 使用 sed -e 替换斜杠
- javascript - 如何在 textarea 中编辑带有标签的 HTML 文档而不显示标签?
- sql - 使用分层查询和 ANSI 连接创建物化视图
- git - 如何在不使用 github 的情况下将本地 git repo 部署到 VPS
- python - KivyMD Layout - 将小部件(来自 python)添加到现有的 BoxLayout
- c++ - Tensorflow C++ api 可以与通过 pip 获得的 tensorflow 的二进制构建一起使用吗?
- python - matplotlib 不会正确渲染乳胶矩阵 bmatrix (很可能没有正确转义)