[英]Ternary operator inside Action<T> not working
有一個Action委托並嘗試在lambdas中使用其中的三元運算符:
Action<string> action = new Action<string>( str => (str == null) ?
Console.WriteLine("isnull") : Console.WriteLine("isnotnull")
給出舊的“僅賦值,減量等允許”錯誤。
這有可能嗎?
你必須這樣做:
var action = new Action<string>(str => Console.WriteLine((str == null) ? "isnull" : "isnotnull"));
Action<string> action = new Action<string>( str =>
{
if (str == null)
Console.WriteLine("isnull");
else
Console.WriteLine("isnotnull");
});
我相信三元運算符必須返回一些東西。 在你的情況下,它不返回任何東西,只是執行一個語句。 正如Reddog所說,你必須把你的三元組放在Console.WriteLine調用中,這實際上是更少的代碼:)
問題不在於lambda,而在於三元運算符中的第二個和第三個表達式必須返回一些東西。 Console.WriteLine
具有void
返回類型,無法按照您的嘗試使用。 解決方案是將三元運算符放在對Console.WriteLine
的調用中:
Console.WriteLine(str == null ? "isnull" : "isnotnull")
您可以在lambda中使用此表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.