【问题标题】:Use of unassigned parameter compiler error, for a variable received from a function out parameter?使用未分配参数编译器错误,对于从函数输出参数接收的变量?
【发布时间】:2021-05-27 22:26:42
【问题描述】:

今天我(错误地)遇到了一个奇怪的编译器错误,我不明白它的原因(可能是编译器问题?)。 .Net Framework 4.0 和 Visual Studio 2019(如果重要)。

确切的错误是TryParse 之后的 if 处的“使用未分配的局部变量‘值’”。 如果我使用s 或将d.s 转换为字符串,代码编译得很好。

using System;
using System.Dynamic;

namespace TestConsoleApp
{
    static class Program
    {
        static void Main(string[] _)
        {
            string s = "1";

            dynamic d = new ExpandoObject();
            d.s = s;

            if (d.s != null && int.TryParse(d.s, out int value))
            {
                if (value == 1)
                {
                    Console.Out.WriteLine("OK!");
                }
            }
        }
    }
}

【问题讨论】:

  • 仅供参考,null 检查是多余的,因为 int.TryParse 正确处理了它。这也将避免编译器错误。是的,对我来说这看起来像一个编译器错误。
  • @TimSchmelter 确实! :O 在我的生产代码中,我使用的是Enum.TryParse,但我测试过,它具有类似的null 输入行为。
  • 顺便说一句,您可以展平两个 if 语句 if (int.TryParse(d.s, out int value) && value == 1) { ... }
  • 这是我的生产代码的过度简化版本

标签: c# .net compiler-errors .net-4.0


【解决方案1】:

乍一看,它看起来像是一个编译器错误。如果你删除了d.s != null-check,无论如何这都是不必要的,它会编译得很好。但我认为这里的评论解释了它: https://github.com/dotnet/roslyn/issues/39489#issuecomment-546003060


很遗憾,这不是错误,这是由于 C# 中存在 true/false 运算符造成的。

您可以在&& 表达式的左操作数下定义一个计算结果为true 的类型,而不计算&& 的右操作数,如下所示:

class C {
  public static U operator==(C c, C d) => null;
  public static U operator!=(C c, C d) => null;
}

class U {
  public static U operator &(U c, U d) => null;
  public static implicit operator U(bool b) => null;
  public static bool operator true(U c) => true;
  public static bool operator false(U c) => false;
    
  public void M(C c, object o) {
    if (c != null && o is string s) {
      s.ToString(); // CS0165: Use of unassigned local variable 's'
    }
  }
}

当处理动态类型的值时,C# 没有关于该类型的静态信息并且它是重载的运算符,因此它假定“更糟糕”的类型——如上例中的 U。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多