今天我遇到了(错误地)一个奇怪的编译器错误,我不明白它的原因(编译器问题可能?). net Framework 4.0和Visual Studio 2019如果这很重要。
正确的错误是"使用未赋值的局部变量'value'";在TryParse
之后的if。如果我使用s
或将d.s
转换为string,代码编译得很好。
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!");
}
}
}
}
}
乍一看像是编译器的bug。如果您删除d.s != null
检查(无论如何都是不必要的),它将编译得很好。但我认为这条评论解释了它:https://github.com/dotnet/roslyn/issues/39489 issuecomment - 546003060
不幸的是,这不是一个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'
}
}
}
当处理动态类型的值时,c#没有关于该类型的静态信息,并且它是重载的操作符,因此它假定为&;-在上面的例子中输入U。