这是关于C#的新引入的空值检查运算符的问题。运营商'?'不能应用于类型'方法组'的操作数
假设我有这样一个接口:
interface ILogger
{
void Log(string message);
}
,并期望一个功能的记录行动:
void DoWork(Action<string> logAction)
{
// Do work and use @logAction
}
为什么我得到下面的编译错误,如果我尝试写:
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);
}
http://stackoverflow.com/questions/32580536/operator-cannot-be-applied-to-operand-of-type-t的可能重复 –
你可以显示'GetLogger()'吗?你的'DoWork()'似乎与你面临的问题无关。 – krillgar
当'logger'为空时,您会期待哪种行为?使'logAction'值为空?使'logAction'忽略传递的字符串(实际上,使其成为=> {}')?不要叫'DoWork(..)'? –