首页 > 解决方案 > 是否可以将以下内容简化为一行?

问题描述

我为一个非常糟糕的标题道歉。我不知道正确的术语,但如果你能告诉我我实际在问什么,我会编辑它。

是否可以像使用自动属性一样连续执行以下操作?:

public class MyClass
{
    static OtherClass _otherClass;
    static OtherClass otherClass => _otherClass ?? (_otherClass = new OtherClass());
}

标签: c#initialization

解决方案


您可以使用Lazy<T>延迟初始化,尽管它不会过多地简化代码:

static Lazy<OtherClass> _otherClassLazy = new Lazy<OtherClass>(() => new OtherClass());

static OtherClass otherClass => _otherClassLazy.Value;

Lazy<T>仅将值初始化一次,并且仅在实际访问时才初始化。

如果你真的想要一行,你可以使用:

static Lazy<OtherClass> otherClass { get; } = new Lazy<OtherClass>(() => new OtherClass());

otherClass.Value以在代码中引用此变量时必须使用为代价。

{ get; } = new OtherClass()如果您只想按需初始化属性,而不是在类本身的初始化期间,则此解决方案更可取。如果构造函数正在做大量工作并且在某些情况下可能不使用该属性,这可能是可取的。


推荐阅读