【问题标题】:Elegant pattern for nullable types可空类型的优雅模式
【发布时间】:2015-11-15 13:24:27
【问题描述】:

我有以下构造:

MyType y = x.HasValue ? f(x) : null;

我知道如果fx 的成员,可以使用一个简单的模式:MyType y = x.?f();

有没有类似的方法可以在不改变f的定义的情况下简化上面的代码?

【问题讨论】:

  • 当取参数为空时,使 f 返回空。 ;)
  • 我更新了问题。
  • 看起来像Maybe Monad
  • 您当前的代码是清晰的。你真的想让保存几个字符变得不那么不稳定吗?如果是,您可以尝试扩展方法。比如说,int? i = null; int? = i.Call(f); 使用扩展方法 static R Call<P>(this P? parameter, Func<P, R> func) { if (parameter.HasValue) return func(parameter.Value); else return default(R); }
  • 我一直在寻找更原生于 C# 的东西,以避免扩展方法和其他任何需要添加更多代码的东西。我想没有必要做这样的事情。

标签: c# ternary-operator c#-6.0 null-conditional-operator


【解决方案1】:

目前(2015 年 11 月),C# 中不存在这种机制。

选项是:

  1. 当参数为null 时,将f 更改为返回null
  2. 制作扩展方法

static R Call<P>(this P? parameter, Func<P, R> func)
{
    if (parameter.HasValue)
        return func(parameter.Value);
    else
        return default(R);
}

【讨论】:

    【解决方案2】:

    我能想到的最接近的东西是空合并运算符'??'

    来自MSDN

    // Set y to the value of x if x is NOT null; otherwise
    // if x == null, set y to -1
    y = x ?? -1;
    

    假设f() 可以处理xnull,如果不是return null,那么你可以只处理MyType y = f(x),这听起来是你最好的选择。请记住,除了更改函数以处理 x 为 null 之外的任何操作都需要您记住自己做,并记住原因,从而为自己创造空间并移除一层抽象。

    另外,f(x) 不采用可为空的类型,因此无论如何都期待一个?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2015-03-18
      • 1970-01-01
      • 2015-07-15
      相关资源
      最近更新 更多