gpt4 book ai didi

c# - 检查子元素之一是否为 null 且不抛出异常的最佳方法

转载 作者:行者123 更新时间:2023-11-30 20:23:57 26 4
gpt4 key购买 nike

我的电话是例如:

var bankacc = workReport.works.customers.bankaccounts.Name;

这意味着 works 可以为 null,customers 可以为 null,bankaccounts 也可以为 null。我不想检查它们是否为空。我可以使用某种方法来检查整个语句,如果为 null 则返回空字符串吗?

编辑:

我正在使用 .NET FM 4.5

最佳答案

我并不是说这是个好主意,但它是一个可能的解决方案 - 扩展方法。

public static class MyExtensions
{
public static TResult IfNotNull<TSource, TResult>(this TSource source, Func<TSource, TResult> function)
where TSource : class where TResult : class
{
if (source == null)
return null;
return function(source);
}
}

和用法:

var bankacc = workReport.IfNotNull(x => x.works)
.IfNotNull(x => x.customers
.IfNotNull(x => x.bankaccounts
.IfNotNull(x => x.Name) ?? string.Empty;

关于c# - 检查子元素之一是否为 null 且不抛出异常的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27746702/

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