Bra*_*nez 96 c# compiler-construction cil dynamic c#-4.0
以下代码导致使用未分配的局部变量"numberOfGroups":
int numberOfGroups;
if(options.NumberOfGroups == null || !int.TryParse(options.NumberOfGroups, out numberOfGroups))
{
numberOfGroups = 10;
}
Run Code Online (Sandbox Code Playgroud)
但是,这段代码工作正常(但ReSharper说这= 10是多余的):
int numberOfGroups = 10;
if(options.NumberOfGroups == null || !int.TryParse(options.NumberOfGroups, out numberOfGroups))
{
numberOfGroups = 10;
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么,还是编译器不喜欢我||?
我把它缩小到dynamic导致问题(options在上面的代码中是一个动态变量).问题仍然存在,为什么我不能这样做?
此代码无法编译:
internal class Program
{
#region Static Methods
private static void Main(string[] args)
{
dynamic myString = args[0];
int myInt;
if(myString == null || !int.TryParse(myString, out myInt))
{
myInt = 10;
}
Console.WriteLine(myInt);
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
但是,此代码可以:
internal class Program
{
#region Static Methods
private static void Main(string[] args)
{
var myString = args[0]; // var would be string
int myInt;
if(myString == null || !int.TryParse(myString, out myInt))
{
myInt = 10;
}
Console.WriteLine(myInt);
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
我没有意识到dynamic这将是一个因素.
Eri*_*ert 72
我很确定这是一个编译器错误.很好找!
编辑:这不是一个错误,正如Quartermeister所示; dynamic可能会实现一个奇怪的true运算符,这可能导致y永远不会被初始化.
这是一个最小的repro:
class Program
{
static bool M(out int x)
{
x = 123;
return true;
}
static int N(dynamic d)
{
int y;
if(d || M(out y))
y = 10;
return y;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为没有理由说这应该是非法的; 如果你用bool替换动态它编译得很好.
我明天正在和C#团队会面; 我会向他们提起这件事.为错误道歉!
Qua*_*ter 52
如果动态表达式的值是具有重载true运算符的类型,则可以取消分配变量.
该||运营商将调用true操作来决定是否评估右侧,然后if语句将调用true操作来决定是否评估其身.对于正常情况bool,这些将始终返回相同的结果,因此将评估一个,但对于用户定义的运算符,没有这样的保证!
在Eric Lippert的复制品的基础上,这是一个简短而完整的程序,它演示了一种情况,即既不会执行路径,也不会有变量的初始值:
using System;
class Program
{
static bool M(out int x)
{
x = 123;
return true;
}
static int N(dynamic d)
{
int y = 3;
if (d || M(out y))
y = 10;
return y;
}
static void Main(string[] args)
{
var result = N(new EvilBool());
// Prints 3!
Console.WriteLine(result);
}
}
class EvilBool
{
private bool value;
public static bool operator true(EvilBool b)
{
// Return true the first time this is called
// and false the second time
b.value = !b.value;
return b.value;
}
public static bool operator false(EvilBool b)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2628 次 |
| 最近记录: |