代码之家  ›  专栏  ›  技术社区  ›  Sarah Vessels

可为空的类型和Resharper警告

  •  7
  • Sarah Vessels  · 技术社区  · 15 年前

    我有以下代码:

    private static LogLevel? _logLevel = null;
    
    public static LogLevel LogLevel
    {
        get
        {
            if (!_logLevel.HasValue)
            {
                _logLevel = readLogLevelFromFile();
            }
    
            return _logLevel.Value;
        }
    }
    
    private static LogLevel readLogLevelFromFile() { ... }
    

    我得到了一个关于 return 关于可能性的陈述 System.InvalidOperationException 建议我查一下 _logLevel 看看是不是 null 第一。然而, readLogLevelFromFile 收益率 LogLevel 不是 LogLevel? 所以没有办法 返回 γ对数级 无效的 . 这只是雷斯哈珀的疏忽,还是我遗漏了什么?

    3 回复  |  直到 15 年前
        1
  •  5
  •   SLaks    15 年前

    这看起来像是一个错误。

    但是请注意,这不是线程安全的。

    The best way to do this is to use a static initializer ,像这样:

    public static LogLevel Instance { get { return Nested.level; } }
    
    class Nested {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested() { }
    
        internal static readonly LogLevel level = readLogLevelFromFile();
    }
    
        2
  •  4
  •   ChaosPandion    15 年前

    您可以将其重构为如下类型:

    return (_logLevel = _logLevel ?? readLogLevelFromFile()).Value;
    

    或者,您可以使用内置的Lazy类型(需要.NET 4.0或您可以自己滚动)。

    public static LogLevel LogLevel
    {
        get { return _logLevel.Value; }
    }
    private static Lazy<LogLevel> _logLevel = new Lazy<LogLevel>(readLogLevelFromFile);
    
        3
  •  0
  •   Brian Genisio    15 年前

    Resharper不够聪明,不能帮你解决问题。我可以想象,这是一件很复杂的事情。

    我更喜欢@chaospanion的重构…