其他分享
首页 > 其他分享> > 标签:Expression.AddChecked和System.Int16

标签:Expression.AddChecked和System.Int16

作者:互联网

给出两条短裤(System.Int16)

short left = short.MaxValue;
short right = 1;

添加它们时,我想获取一个OverflowException.

checked(left+right)

不起作用,因为从左到右的结果是一个Int32.

checked((short)(left+right))

如预期般运作.

我的问题是,使用表达式树,“把戏”不起作用:

var a = Expression.Constant(left);
var b = Expression.Constant(right);
var sum = Expression.ConvertChecked(Expression.Add(a, b), typeof(short));
var l = Expression.Lambda(sum);
var f = (Func<short>)l.Compile();

调用f()不会引发溢出异常,而是返回-32768.怎么了?

解决方法:

问题是加法操作要以short short方式进行(即使在C#中不存在,IL也可能存在)-然后分别进行转换.这由完整的程序显示-即使不进行转换,结果也为-32768:

using System;
using System.Linq.Expressions;

class Test
{
    static void Main(string[] args)
    {
        short left = short.MaxValue;
        short right = 1;
        var a = Expression.Constant(left);
        var b = Expression.Constant(right);
        var sum = Expression.Add(a, b);
        var convert = Expression.ConvertChecked(sum, typeof(short));
        var convertLambda = Expression.Lambda<Func<short>>(convert);
        var convertFunc = convertLambda.Compile();
        Console.WriteLine("Conversion: {0}", convertFunc());
        var sumLambda = Expression.Lambda<Func<short>>(sum);
        var sumFunc = sumLambda.Compile();
        Console.WriteLine("Sum: {0}", sumFunc());
    }
}

如果让它先进行int int加法运算,然后进行转换,则将引发溢出异常:

using System;
using System.Linq.Expressions;

class Test
{
    static void Main(string[] args)
    {
        short left = short.MaxValue;
        short right = 1;
        var a = Expression.Constant((int) left);
        var b = Expression.Constant((int) right);
        var sum = Expression.Add(a, b);
        var convert = Expression.ConvertChecked(sum, typeof(short));
        var convertLambda = Expression.Lambda<Func<short>>(convert);
        var convertFunc = convertLambda.Compile();
        Console.WriteLine("Conversion: {0}", convertFunc());
        var sumLambda = Expression.Lambda<Func<int>>(sum);
        var sumFunc = sumLambda.Compile();
        Console.WriteLine("Sum: {0}", sumFunc());
    }
}

我不知道为什么AddChecked不能正常工作…看起来像个bug :(可能使用the overload which allows the Method to specified would work,但是我不确定…

标签:c,expression-trees
来源: https://codeday.me/bug/20191108/2004632.html