[英]Is there a way to Imitate C# 6 Null-Conditional operator in C# 5
[英]c# Null-conditional Operator
我正在嘗試使用Null條件運算符( ?
),但是我不確定在哪里將其正確地放置為separators.Contains(textLine[(index - 1)])
。 我想說“如果(textLine[(index - 1)])
不為null,請繼續”。 一些幫助?
這不是空條件運算符的工作方式。
空條件運算符,如果標有前綴?的父級之一,則僅返回null而不是異常。 是==空
例:
var g1 = parent?.child?.child?.child;
if (g1 != null) // TODO
您需要的是一個簡單的中頻條件
if (!string.IsNullOrEmpty(textLine))
{
// Work here
}
MSDN文檔的第二個示例應回答您的問題:
Customer first = customers?[0]; // null if customers is null
如果您要在數組中的值為null時不調用contains方法,則必須首先對其進行檢查。
// requires possible bounds checking
char? test = textLine?[index-1];
if (test != null && separaters.Contains(test.Value))
使用linq:
// does not require bounds checking
char test = textLine?.Skip(index-1).FirstOrDefault() ?? default(char);
if (test != default(char) && separaters.Contains(test))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.