【问题标题】:How can i re write the null checking line since it's not supporting in unity?我如何重新编写空检查行,因为它不支持统一?
【发布时间】:2017-06-04 01:43:05
【问题描述】:
XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");
            XNamespace ns = "http://www.w3.org/2000/svg";

            var list = document.Root.Descendants(ns + "rect").Select(e => new {
                Style = e.Attribute("style").Value.Substring(15, 7),
                Transform = e.Attribute("transform")?.Value,
                Width = e.Attribute("width").Value,
                Height = e.Attribute("height").Value,
                X = e.Attribute("x").Value
            });

在 csharp 中它工作正常。 但是在统一视觉工作室中,我遇到了错误:

e.Attribute("transform")?.Value.Substring(18, 43)

功能“空传播运算符”在 C# 4 中不可用。请使用语言版本 6 或更高版本。

在 csharp 中我不需要更改任何内容。

我统一使用的视觉工作室(与 csharp 相同)是:14.0.24531.01 Update 3 和 visual c# 2015

也许我需要更改行检查是否为其他内容?

【问题讨论】:

  • 这与 VS 无关,而是与 Unity 中使用的 C# 编译器有关 - 作为错误状态,它仅支持 C# 4.0。所以你必须编写“旧式”空检查,例如:if(e.Attribute("transform") != null)
  • @UnholySheep 但是我在哪里以及如何添加这个旧的空检查?我将行更改为原来的: Transform = e.Attribute("transform").Value.Substring(18, 43) 但现在在哪里添加 if(e.Attribute("transform") != null) i can' t 只需在 e.Attribute 行上方添加一行。
  • 你把它放在 if 语句中。你还在为此苦恼吗?
  • @Programmer 是的,仍然不明白 if(e.Attribute("transform") != null) 的放置位置/方式

标签: c# unity3d unity5


【解决方案1】:

您已经知道为什么不能使用 ?.,这是因为 Unity 不支持支持 ?. 的 C# 版本。

UnholySheep 评论建议使用 if 语句,但我认为你不能在这里使用它。

您可以使用三元运算符检查null

用途:

Transform = e.Attribute("transform") != null ? e.Attribute("transform").Value : "",

如果您仍然感到困惑。这是整个代码:

XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");
XNamespace ns = "http://www.w3.org/2000/svg";

var list = document.Root.Descendants(ns + "rect").Select(e => new
{
    Style = e.Attribute("style").Value.Substring(15, 7),
    Transform = e.Attribute("transform") != null ? e.Attribute("transform").Value : "",
    Width = e.Attribute("width").Value,
    Height = e.Attribute("height").Value,
    X = e.Attribute("x").Value
});

【讨论】:

    【解决方案2】:

    您可以使用三元运算符?: 以老式方式进行操作,并且我会在集合初始化程序之外获取属性,因此您不必对它进行两次索引:

    var list = document.Root.Descendants(ns + "rect").Select(e => 
        var tr = e.Attribute("transform");
    
        new {Style = e.Attribute("style").Value.Substring(15, 7),
        Transform = (tr != null) ? tr.Value : null,
        Width = e.Attribute("width").Value,
        Height = e.Attribute("height").Value,
        X = e.Attribute("x").Value
    });
    

    如果将 Visual Studio 版本升级到 2015 或 2017,则可以使用 null 条件运算符。

    【讨论】:

    • 不,升级 Visual Studio 版本将无法在 Unity 中使用 C# 6 - 它有自己的编译器,目前不支持 C# 6(尽管计划在 Mono Runtime 的未来版本中使用升级)
    • 它不工作。您不能在新的 { 之前添加 var 会出现很多错误。
    猜你喜欢
    • 1970-01-01
    • 2010-09-12
    • 2014-05-18
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2020-11-27
    相关资源
    最近更新 更多