在我的机器上安装了Visual Studio 2015 Update 1之后,我发现我的一些单元测试失败了。经过一番调查,我能够将问题简化为以下代码行:
Expression<Func<GameObject, bool>> expression = t => t.X == 0 && t.Y == 0 && t.GameObjectType == GameObjectType.WindMill;
当悬停在表达式变量上时,Visual Studio的不同版本显示结果不同:
VS 2015:
![VS 2015](https://istack.dev59.com/GnKvt.webp)
![VS 2015 Update 1](https://istack.dev59.com/Q1BbS.webp)
我使用以下代码复现了问题:
class Program
{
static void Main(string[] args)
{
var gameObjects = new List<GameObject> {
new GameObject { X = 0, Y = 0, GameObjectType = GameObjectType.WindMill },
new GameObject { X = 0, Y = 1, GameObjectType = GameObjectType.Pipe },
new GameObject { X = 0, Y = 2, GameObjectType = GameObjectType.Factory }
};
var gameObjectsQueryable = gameObjects.AsQueryable();
Expression<Func<GameObject, bool>> expression = t => t.X == 0 && t.Y == 0 && t.GameObjectType == GameObjectType.WindMill;
var result = gameObjectsQueryable.Where(expression);
var resultAsList = result.ToList();
foreach (var item in resultAsList)
{
Console.WriteLine(item);
}
//Obtain the t.GameObjectType == GameObjectType.WindMill part
var binaryExpression = expression.Body as BinaryExpression;
var right = binaryExpression.Right;
var binaryExpression2 = right as BinaryExpression;
var right2 = binaryExpression2.Right;
if (right2 is UnaryExpression)
{
Console.WriteLine("Found UnaryExpression (This happens when the solution is build with VS2015)...");
var right2Unary = binaryExpression2.Right as UnaryExpression;
var right2Constant = right2Unary.Operand as ConstantExpression;
CheckIfConsantIsAsExpected(right2Constant);
}
else
{
Console.WriteLine("Found ConstantExpression (This happens when the solution is build with VS2015 Update 1)...");
var right2Constant = binaryExpression2.Right as ConstantExpression;
CheckIfConsantIsAsExpected(right2Constant);
}
Console.ReadKey();
}
public static void CheckIfConsantIsAsExpected(ConstantExpression expression)
{
if (expression.Value.Equals(GameObjectType.WindMill))
{
Console.WriteLine($"The value is the enum we expected :), : {expression.Value}");
}
else
{
Console.WriteLine($"The value is not the enum we expected :(, : {expression.Value}");
}
}
}
public class GameObject
{
public int X { get; set; }
public int Y { get; set; }
public GameObjectType GameObjectType { get; set; }
public override string ToString()
{
return $"{X},{Y}: {GameObjectType}";
}
}
public enum GameObjectType
{
WindMill = 100,
Pipe = 200,
Factory = 300
}
在VS 2015中,它将进入UnaryExpression路径,在VS 2015 Update 1中,它将进入ConstantExpression路径。如果您在VS 2015上编译解决方案,然后将已编译的.exe文件复制到VS 2015 Update 1系统中,它将与VS 2015版本相同运行(因此也是UnaryExpression路径)。这表明它与JIT无关,而是与构建相关。我的问题是这是否是有意的?(因为它可能会在简单重新编译解决方案时破坏现有代码)
Right
也是常量表达式。 - Bagherani