我有以下代码:
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
的 ReSharper 警告,它建议我检查 _logLevel
看它是否是null
首先。但是,readLogLevelFromFile
返回 LogLevel
,而不是 LogLevel?
,因此当 return
语句无法到达时_logLevel
为 null
。这只是 ReSharper 的疏忽,还是我遗漏了什么?
最佳答案
这看起来像是 Resharper 中的错误。
但是请注意,这不是线程安全的。
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();
}
关于c# - 可空类型和 ReSharper 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835671/