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

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

今天我(错误地)遇到了一个奇怪的编译器错误,我不明白它的原因(也许是编译器问题?)。 .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!");
                }
            }
        }
    }
}

最佳答案

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

不幸的是,这不是错误,这是由 true 的存在引起的。/false C#中的运算符。
您可以定义一个计算结果为 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。

关于c# - 对于从函数输出参数接收的变量,使用未分配的参数编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66370587/

相关文章:

C#、XNA 和单声道。这一切都会奏效吗?

c# - WCF 和传递 Windows 凭据

.net - .net 的首选单元测试隔离框架

java - 如何找出编译时加载了哪个类?

c# - zip 文件内的内容

c# - 有没有一种直接的方法来检索浏览器呈现但未在实际 html 文件中硬编码的文本?

javascript - 第 6 行中未关闭的 INDENT (CoffeeScript) 编译器错误

android - Google App Engine : DuplicateFileException

c# - C#调用类函数时出现NullReferenceException

.net - 如何在 .Net Core 中引用 Microsoft.Office.Core (office.dll)