调用链中的空合并 [英] Null coalescing within an invocation chain
问题描述
如果我有对象的一个长长的清单,每有一个LINQ的,其中内返回null条款,如可能性
If I have a long list of objects that each has the possibility of returning null within a "Linq where" clause, e.g.
SomeSource.Where(srcItem=>(srcItem.DataMembers["SomeText"].Connection.ConnectedTo as Type1).Handler.ForceInvocation == true));
索引可以返回空值和为运营商可能返回null。这是可能的对象没有连接(即该属性为null)。
。如果一个空的任何地方遇到过,我想在where子句返回假,对于项目进行评估。相反,它有一个空引用异常中止。
the indexer can return null and the "as" operator may return null. It is possible that the object does not have a connection (ie. The property is null). If a null is encountered anywhere, I would like the where clause to return "false" for the item being evaluated. Instead, it aborts with a null reference exception.
在我看来,这将是做作到一个C#表达式中表达出来。我不喜欢创建一个多行语句或为其创建一个单独的FUNC。
有一些使用我失踪的空合并运算符的?
It appears to me that this would be contrived to express within a single C# expression. I don't like to create a multi line statement or create a separate func for it. Is there some use of the null coalescing operator that I'm missing?
推荐答案
您正在寻找的?
运营商(或者是它?
那些酮,反正),这并不在C#中存在(虽然它是一个经常被请求的功能,根据埃里克利珀)。
You're looking for the .?
operator (or is it ?.
—one of those, anyway), which does not exist in C# (though it is an often-requested feature, according to Eric Lippert).
唯一的可能的建议,我已经是编写需要一个表达式的方法和用途的是的检查任何空值。但是,这会在性能成本。无论如何,它可能看起来像:
The only possible suggestion I have is to write a method that takes an expression and uses it to check for any nulls. But this will come at a performance cost. Anyway, it might look like:
T TryOrDefault<T>(Expression<Func<T>> expression)
{
// Check every MemberExpression within expression one by one,
// looking for any nulls along the way.
// If a null is found, return default(T) or some default value.
// Otherwise...
Func<T> func = expression.Compile();
return func();
}
这篇关于调用链中的空合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!