编程语言
首页 > 编程语言> > c# – 非重复的说法:除非对象为null,否则访问此对象的成员

c# – 非重复的说法:除非对象为null,否则访问此对象的成员

作者:互联网

参见英文答案 > Safe Navigation Operator in C#?                                     4个
假设我有一套车,每辆车都有一个方向盘.我想编写一行代码,在集合中查找汽车并返回其方向盘,如果汽车不在集合中,则返回null.像这样的东西:

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

有没有办法在表达式中不使用found和null两次执行此操作?我不喜欢这里重复的气味.

解决方法:

在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上调用扩展方法,但它确实有效.这是一种风格偏好,而不是技术限制.

标签:c,idiomatic,null-coalescing
来源: https://codeday.me/bug/20190717/1489540.html