【问题标题】:Unable to use inline out declaration无法使用 inline out 声明
【发布时间】:2020-04-01 08:34:24
【问题描述】:

我正在 VS2019 中创建新项目,目标是 .NET 4.7.1。 以下是我用于 out 参数内联声明的示例代码。

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = "-1.5E5";
            bool b = decimal.TryParse(a, out d number);
        }
    }
}

但是,编译器抱怨:

The type or namespace name 'd' could not be found (are you missing a using directive or an assembly reference?)

为了使用 C# 7 功能,除了指定目标 4.7 之外还有什么特别的吗?

【问题讨论】:

  • “out d number”中的d是什么?应该是“out var number”还是“out decimal number”?

标签: c# c#-7.0


【解决方案1】:

你必须定义类型或使用var关键字

    class Program
    {
        static void Main(string[] args)
        {
            string a = "-1.5E5";
            bool b = decimal.TryParse(a, out var  d );
        }
    }

ps。十进制解析-1.5E5会得到0,避免这种情况你colud使用double.Parse

【讨论】:

    【解决方案2】:

    你做错了。声明以这种方式工作:Type Name,而您使用了 Name Type 和无效类型。你应该使用的是:

    bool b = decimal.TryParse(a, out var d);
    

    也可以使用decimal 代替var,当然:)

    【讨论】:

      【解决方案3】:

      我相信你做错了。 当你使用 TryParse 时,你确实使用了一个临时变量来传递 TryParse 的结果(在成功的情况下)。

      我的建议是:

      bool result  = false;
      bool question = decimal.TryParse(yourInputVar, out result);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-14
        • 2018-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-25
        • 1970-01-01
        相关资源
        最近更新 更多