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

C# 在不实例化类的情况下访问字段,c#,tdd,domain-driven-design,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 }

假设我有一门课是这样的:

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
,如果
的每个实例都需要一个字段或属性作为id引用该静态
Guid
,如

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

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

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

由于
\u id
只读的
我假设每个
Offer1
-对象都有相同的id,是correkt吗?@Ackdari,是的,这是正确的。也许您可以实现一个静态getter方法:public static Guid id(){return _id;}(这仍然要求_id是静态的)这些报价是否有不同的行为?此外,将报价视为实体是否有帮助?例如
offer1=offerpositionory.findById(StandardOffers.offer1)
其中
StandardOffers
是一个枚举。出于配置目的使用多个静态/单例类似乎不是一个好主意。您也可以使用
StandardOffers。offer1
其中
StandardOffers
是StandardOfferFactory/Provider服务的一个实例(可以实现
I提供标准产品
)。如果它是一个常量值,我看不出它在创建时会如何影响可测试性static@w0051977如果我的答案解决了你的问题,请把它标为答案