gpt4 book ai didi

c# - 空参数替代C#6.0

转载 作者:太空狗 更新时间:2023-10-29 18:21:33 26 4
gpt4 key购买 nike

我看到了 C# 6 中的新功能,它允许代码跳过 if 语句以进行 null 检查。

例如:

return p?.ToString();

如何调用需要将 p 作为参数传递给的方法(没有旧的 if/else)?

我通常使用 C# pre-6 编写此代码的方式:

 p != null ? callmethod(p) : null

C# 6 中有更好的东西吗?

最佳答案

您可以使用扩展方法 - 您可以将其推广到任何情况。这是有效的,因为 C# 允许扩展方法使用 this 参数的 null 值(令人惊讶!),而对于普通的实例方法,您将获得 NullReferenceException.

在 C# 6 中使用 ?.“安全导航”运算符之前,我在自己的项目中使用了一些类似的东西:

public static class Extensions
{
public static TRet NullSafeCall<TValue,TRet>( this TValue value, Func<TValue,TRet> func )
where TValue : class
where TRet : class
{
if( value != null ) return func( value );
return null;
}
}

这样使用:

return p.NullSafeCall( callmethod );

如果您需要将超过 1 个参数传递到后续的 func 中,它还支持使用 lambda:

String foo = "bar";
return p.NullSafeCall( v => callmethod2( v, foo ) );

在您的示例中,您使用了 String.IsNullOrEmpty 而不是 != null,可以像这样添加:

public static class Extensions
{
public static TRet NullSafeCall<TValue,TRet>( this TValue value, Func<TValue,Boolean> guard, Func<TValue,TRet> func )
where TValue : class
where TRet : class
{
if( guard( value ) ) return func( value );
return null;
}
}

用法:

return p.NullSafeCall( v => String.IsNullOrEmpty( v ), v => callmethod( v ) );

当然,您可以链接它:

return p
.NullSafeCall( callmethod2 )
.NullSafeCall( callmethod3 )
.NullSafeCall( v => callmethod4( v, "foo", bar ) );

关于c# - 空参数替代C#6.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45116537/

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