C#延迟加载的自动属性 [英] C# Lazy Loaded Automatic Properties

查看:135
本文介绍了C#延迟加载的自动属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,

是否可以将自动属性转换为具有指定默认值的延迟加载的自动属性?

Is there a way to turn an automatic property into a lazy loaded automatic property with a specified default value?

从本质上讲,我正在尝试将此...

Essentially, I am trying to turn this...

private string _SomeVariable

public string SomeVariable
{
     get
     {
          if(_SomeVariable == null)
          {
             _SomeVariable = SomeClass.IOnlyWantToCallYouOnce();
          }

          return _SomeVariable;
     }
}

更改为其他内容,我可以在其中指定默认值,它会自动处理其余内容...

into something different, where I can specify the default and it handles the rest automatically...

[SetUsing(SomeClass.IOnlyWantToCallYouOnce())]
public string SomeVariable {get; private set;}

推荐答案

没有.自动实现的属性仅用于实现最基本的属性:具有getter和setter的后备字段.它不支持这种类型的自定义.

No there is not. Auto-implemented properties only function to implement the most basic of properties: backing field with getter and setter. It doesn't support this type of customization.

但是,您可以使用4.0 Lazy<T> 类型来创建这种模式

However you can use the 4.0 Lazy<T> type to create this pattern

private Lazy<string> _someVariable =new Lazy<string>(SomeClass.IOnlyWantToCallYouOnce);
public string SomeVariable => _someVariable.Value;

此代码将在第一次调用Value表达式时延迟计算_someVariable的值.它只会被计算一次,并将缓存该值以供将来使用Value属性

This code will lazily calculate the value of _someVariable the first time the Value expression is called. It will only be calculated once and will cache the value for future uses of the Value property

这篇关于C#延迟加载的自动属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆