這是關於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(..)'? –