在不实例化类的情况下访问字段

时间:2019-03-18 14:05:23

标签: c# tdd domain-driven-design

说我有一个这样的课程:

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

这更多是一个设计问题。

1 个答案:

答案 0 :(得分:2)

我建议您使用一个静态字段来保存Guid,如果Offer1的每个实例都需要一个字段或属性作为ID以引用该静态Guid,例如< / p>

public class Offer1
{
    internal static readonly Guid ID = new Guid(...);

    private Guid _id => ID;
    // or
    private readonly Guid _id = ID;
}

propety变量的优点是,并非每个实例都需要Guid的内存。由于Guid是一种值类型,因此每个实例都会为该GUId分配一个字段。

相关问题