这是关于C#新引入的空检查运算符的问题.
假设我有一个界面,如:
interface ILogger
{
void Log(string message);
}
Run Code Online (Sandbox Code Playgroud)
和一个期望记录操作的函数:
void DoWork(Action<string> logAction)
{
// Do work and use @logAction
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试编写,为什么会出现以下编译器错误:
void Main(string[] args)
{
ILogger logger = GetLogger(); // Assume GetLogger() may return null
//
// Compiler error:
// Operator '?' cannot be applied to operand of type 'method group'
//
DoWork(logger?.Log);
}
Run Code Online (Sandbox Code Playgroud) I have a situation where a project I'm maintaining contains a piece of code where:
A thread T1 periodically updates a field of type List<String> then adds a value to a LinkedBlockingQueue:
// ctor
List<String> list = null;
queue = new LinkedBlockingQueue(); // Integer.MAX_VALUE capacity
// Thread T1
list = getNewList();
queue.offer(/* some value */);
Run Code Online (Sandbox Code Playgroud)Another thread T2 periodically polls queue and, upon receiving a certain value, reads list:
// Thread T2
Object value = queue.poll();
if (Objects.equals(value, …Run Code Online (Sandbox Code Playgroud)