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