在 C# 6.0 中访问 Private 属性 值而不创建它

Accessing Private Property value in C# 6.0 without creating it

我知道从 WebConfigurationManager 读取数据很慢,所以我想尽量减少使用它。

假设我的代码中有以下只读 属性:

public string SiteLogo {
    get {
        return WebConfigurationManager.AppSettings["SITE_LOGO"];
    }
}

在 C# 6.0 中,我可以缩短它以便 "getter" 具有默认值:

public string SiteLogo { get; } =  WebConfigurationManager.AppSettings["SITE_LOGO"];

看起来,每次实例化 class 时都会调用此方法,无论是否使用过 属性。

看起来最有效的调用仍然是声明一个 Private 变量以在 属性:

中使用
public string SiteLogo
{
    get
    {
        if (String.IsNullOrEmpty(_siteLogo))
        {
            _siteLogo = WebConfigurationManager.AppSettings["SITE_LOGO"];
        }
        return _siteLogo;
    }
}
private string _siteLogo;

这仍然需要我为我的所有 getter 创建私有变量,这似乎过于繁琐。

我放弃了使用 Session 变量的想法,因为读取它并将其转换为 String 似乎仍然会产生更多开销。

如果需要,我希望看到一种自动分配私有 属性 的方法。

如果编译器调用每个 属性 的私有字段 #this,我可以使用以下内容:

public string SiteLgo
{
    get
    {
        if (String.IsNullOrEmpty(#this))
        {
            #this = WebConfigurationManager.AppSettings["SITE_LOGO"];
        }
        return #this;
    }
}

更好的是,我永远不需要明确告诉代码块给 return 私人 属性,因为那是 getter 的工作:

public string SiteLogo
{
    get
    {
        if (String.IsNullOrEmpty(#this))
        {
            #this = WebConfigurationManager.AppSettings["SITE_LOGO"];
        }
    }
}

如果目前存在执行此操作的技术,我不知道如何称呼它来查找它。

我是否错过了更好的方法来完成我想要的事情(无需创建就可以访问私有值)?

您错过了 .NET 4.0 中引入的一些 class:Lazy<T>

private readonly string _siteLogo = new Lazy<string>(() => WebConfigurationManager.AppSettings["SITE_LOGO"]);

// Lazy<T>.Value will call the factory delegate you gave
// as Lazy<T> constructor argument
public string SiteLogo => _siteLogo.Value;

顺便说一句,我不会在这种情况下使用延迟加载...在一天结束时,应用程序设置已经加载到内存中,您无法从文件中访问。

事实上,AppSettings是一个NameValueCollection,它使用散列码来存储密钥(taken from MSDN):

The hash code provider dispenses hash codes for keys in the NameValueCollection. The default hash code provider is the CaseInsensitiveHashCodeProvider.

换句话说,访问AppSettings具有时间复杂度O(1)(常量)。

如果您需要以某种方式解析设置以避免每次都重新解析它们,我会使用延迟加载。