【问题标题】:C# 6 safe navigation not working in VS2015 previewC# 6 安全导航在 VS2015 预览版中不起作用
【发布时间】:2014-12-28 16:48:21
【问题描述】:

我的代码中有以下属性

public float X {
    get {
        if (parent != null)
            return parent.X + position.X;
        return position.X;
    }
    set { position.X = value; }
}

我希望将getter转换为

    get {
        return parent?.X + position.X;
    }

但我收到以下错误:Cannot implicitly convert type 'float?' to 'float'. An explicit conversion exists (are you missing a cast?)

是我做错了什么还是现在不可用?

【问题讨论】:

    标签: c# roslyn c#-6.0


    【解决方案1】:

    parent?.X 的类型是 float?,您将其添加到 float - 生成另一个 float?。这不能隐式转换为float

    虽然 Yuval 的回答应该有效,但我个人会使用类似的东西:

    get
    {
        return (parent?.X ?? 0f) + position.X;
    }
    

    get
    {
        return (parent?.X).GetValueOrDefault() + position.X;
    }
    

    我不确定你的设计,请注意 - 你在 getter 中添加了一些东西,但在 setter 中没有添加,这很奇怪。这意味着:

    foo.X = foo.X;
    

    ...如果parent 为非空且X 值非零,则不会是空操作。

    【讨论】:

    • 这是有道理的。由于某些原因,我没有想到值类型是不可为空的,并且我在 elvis 运算符上看到的示例适用于引用类型。
    【解决方案2】:

    如果父级为null,则在您的情况下使用空传播运算符将尝试返回null。 这只有在float 可以为空时才有可能,因此float?

    您可以改为:

    get 
    {
       return parent?.X + position.X ?? position.x;
    }
    

    如果 parent 返回 null,这将使用 null-coalescing 运算符作为后备。

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 2015-06-05
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 2017-11-12
      • 2016-03-14
      相关资源
      最近更新 更多