gpt4 book ai didi

c# - 调用链中的空合并

转载 作者:行者123 更新时间:2023-11-30 21:17:08 24 4
gpt4 key购买 nike

如果我有一长串对象,每个对象都有可能在“Linq where”子句中返回 null,例如

 SomeSource.Where(srcItem=>(srcItem.DataMembers["SomeText"].Connection.ConnectedTo as Type1).Handler.ForceInvocation == true));

索引器可以返回 null,而“as”运算符可能返回 null。对象可能没有连接(即属性为空)。如果在任何地方遇到 null,我希望 where 子句为正在评估的项目返回“false”。相反,它会因空引用异常而中止。

在我看来,这将被设计为在单个 C# 表达式中表达。我不喜欢创建多行语句或为其创建单独的函数。是否有一些我缺少的空合并运算符的使用?

最佳答案

您正在寻找 .? 运算符(或者它是 ?. — 无论如何),它在 C# 中不存在(尽管它是根据 Eric Lippert 的说法,这是一项经常被要求的功能。

我唯一可能的建议是编写一个采用表达式并使用检查任何空值的方法。但这将以性能成本为代价。无论如何,它可能看起来像:

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();
}

关于c# - 调用链中的空合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4958133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com