不重复的说法:除非对象为空,否则访问该对象的成员

Non-repetitive way of saying: access this object's member unless the object is null

假设我有一组汽车,每辆汽车都有一个方向盘。我想写一行代码来查找集合中的汽车和 returns 它的方向盘,或者 returns null 如果汽车不在集合中。像这样:

Car found = // either a Car or null
SteeringWheel wheel = (found == null ? null : found.steeringwheel);

有没有办法不用在表达式中两次使用 foundnull 来做到这一点?我不喜欢这里重复的味道。

C# 6.0 可以稍等一下,然后使用空条件(a.k.a。安全导航)运算符,?.:

SteeringWheel wheel = FindCar()?.steeringwheel;

在 c# 6 到来之前没有明显的改进,但在那之前你可以在扩展方法中隐藏不愉快。

void Main() {
    Car found = null;// either a Car or null
    SteeringWheel wheel = found.MaybeGetWheel();
}

public static class CarExtensions {
    internal static SteeringWheel MaybeGetWheel(this Car @this) {
        return @this != null ? @this.steeringwheel : null;
    }
}

有人说您不应该允许在 null 上调用扩展方法,但它确实有效。这是风格偏好,不是技术限制。

使用 linq 你可以做到

var steeringwheel = cars.Where(c => c.name = "foo")
                        .Select(c => c.steeringwheel)
                        .SingleOrDefault();