我如何在 C# 6 中初始化 class 上的 属性

How do i initialise a property on a class in C# 6

我有一台使用某些服务的 class。我需要在创建 class 时实例化每个服务。在 C# 6 中,我可以看到两种执行此操作的方法,但我不确定哪种方法是正确的...

protected static SomeServiceType Service => new SomeServiceType();

或者我可以使用自动属性初始化程序...

protected static SomeServiceType Service { get;} = new SomeServiceType();

每种方法的 advantages/drawbacks 是什么? 非常感谢

我相信

  • 前者 ("Expression-bodied members") 调用 new SomeServiceType() 每次读取 属性
  • 后者("Auto-property initializers")在实例化时调用它一次,并且每次读取属性时returns创建的实例。

听起来你想要后者。