Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对于从函数输出参数接收的变量,是否使用未分配参数编译器错误?_C#_.net_Compiler Errors_.net 4.0 - Fatal编程技术网

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

C# 对于从函数输出参数接收的变量,是否使用未分配参数编译器错误?,c#,.net,compiler-errors,.net-4.0,C#,.net,Compiler Errors,.net 4.0,今天我(错误地)遇到了一个奇怪的编译器错误,我不明白它的原因(可能是编译器问题?)。Net Framework 4.0和Visual Studio 2019(如果有必要的话) 确切的错误是TryParse之后的if处的“使用未分配的局部变量'value'”。 如果我使用s或将d.s转换为字符串,则代码可以很好地编译 using System; using System.Dynamic; namespace TestConsoleApp { static class Program

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

确切的错误是
TryParse
之后的if处的“使用未分配的局部变量'value'”。 如果我使用
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
-检查,这是不必要的,它将编译良好。但我认为这里的评论解释了这一点:


不幸的是,这不是一个bug,这是由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'
    }
  }
}

在处理dynamic类型的值时,C#没有关于该类型的静态信息,并且它的运算符重载,因此它假设“更差”类型,如上面的示例中的U。

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