静态类C#中的惰性属性初始化 [英] Lazy Property Initialization in static class C#

查看:58
本文介绍了静态类C#中的惰性属性初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已收到此代码

public static class Logger
{
    public static Func<ILogger> LoggerFactory;
    private static readonly Lazy<ILogger> _log = new Lazy<ILogger>(LoggerFactory);

    public static ILogger Instance
    {
        get
        {
            return _log.Value;
        }
        public static ILogger ConfigureLogging(string AppName, Version AppVersion)
        {
             // stuff
        }
    }
}

此静态类在应用程序中使用:

This static class is used in the application:

Logger.LoggerFactory = () => Logger.ConfigureLogging(AppName, AppVersion);
Logger.Instance.Information("Starting application");

我希望第一行设置LoggerFactory;但是,第一次尝试写入日志时,由于尚未设置静态Func LoggerFactory,因此引发了异常.

I would expect the first row to set the LoggerFactory; however on the first attempt of writing to the log, an exception has thrown because the static Func LoggerFactory hasn't been set yet.

此代码有什么问题?

谢谢

推荐答案

对此的快速而肮脏的解决方法是:

The quick and dirty fix for this would be to do this:

private static readonly Lazy<ILogger> _log = new Lazy<ILogger>(() => LoggerFactory());

Lazy 具有一个函数,该函数将在您首次尝试访问 Value 时执行,但是在您的代码中您将其传递为 null 因为您尚未初始化 LoggerFactory .类中的静态初始化程序将在第一次访问任何静态字段之前运行,因此,您尝试访问 LoggerFactory 的尝试将触发您的 _log 字段进行初始化(如果有的话)尚未)),此时 LoggerFactory 为null.参见此处,以获取有关静态初始化的一些讨论.

Lazy takes a function that will be executed when you first try to access the Value, but in your code you are passing it null because you haven't yet initialized LoggerFactory. The static initializer in your class will run before the first time any of the static fields are accessed, so your attempt to access LoggerFactory will trigger your _log field to initialize (if it hasn't already) at which point LoggerFactory is null. See, for example, here for some discussion on static initialization.

您可以推迟访问 LoggerFactory ,但将其包装在函数中.

You can defer accessing LoggerFactory but wrapping it in a function.

这篇关于静态类C#中的惰性属性初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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