首页 > 解决方案 > 在不实例化类的情况下访问字段

问题描述

假设我有这样的课程:

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

这更像是一个设计问题。

标签: c#tdddomain-driven-design

解决方案


我建议您使用一个静态字段来保存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 分配一个字段。


推荐阅读