【问题标题】:Accessing a field without instantiating a class在不实例化类的情况下访问字段
【发布时间】:2019-03-18 14:05:23
【问题描述】:

假设我有这样的课程:

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

这更像是一个设计问题。

【问题讨论】:

  • 因为_idreadonly 我假设每个Offer1-object 都有相同的ID,是不是更正?
  • @Ackdari,是的,这是正确的。
  • 也许你可以实现一个静态getter方法:public static GUID ID() {return _id;}(这仍然需要_id是静态的)
  • 这些优惠有不同的行为吗?此外,将报价视为实体不是很有帮助吗?例如。 offer1 = offerRepository.findById(StandardOffers.Offer1) 其中StandardOffers 是一个枚举。出于配置目的使用多个静态/单例类似乎不是一个好主意。您还可以拥有standardOffers.offer1,其中standardOffers 是StandardOfferFactory/Provider 服务的一个实例(可以实现IProvideStandardOffers)。
  • 如果它是一个常量值,我看不出它在设为静态时会如何影响可测试性

标签: c# tdd domain-driven-design


【解决方案1】:

我建议您使用一个静态字段来保存Guid,如果Offer1 的每个实例都需要一个字段或属性来让id 引用该静态Guid,例如

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

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

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

【讨论】:

  • @w0051977 如果它解决了您的问题,请将我的答案标记为答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
  • 2011-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
相关资源
最近更新 更多