1

我有以下构造:

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

我知道如果f是以下成员可以使用的简单模式xMyType y = x.?f();

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

4

2 回答 2

0

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

选项是:

  1. 更改f为返回null时参数null
  2. 做一个扩展方法

static R Call<P>(this P? parameter, Func<P, R> func)
{
    if (parameter.HasValue)
        return func(parameter.Value);
    else
        return default(R);
}
于 2015-11-16T15:41:54.717 回答
0

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

来自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()可以处理x存在nullreturn null如果不能处理,那么你可以做MyType y = f(x),这听起来是你最好的选择。请记住,除了更改函数以处理 x 为空之外的任何操作都需要您记住自己做,并记住原因,从而为自己创造空间并移除一层抽象。

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

于 2015-12-15T07:09:04.603 回答