对于从函数输出参数接收的变量,使用未分配的参数编译器错误?

mBa*_*dos 5 .net c# compiler-errors .net-4.0

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

确切的错误是“使用未分配的局部变量‘值’”在TryParse. 如果我使用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!");
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 3

乍一看,它看起来像是一个编译器错误。如果删除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'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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