using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<float, uint>> expr = x => (uint) x;
Func<float,uint> converter1 = expr.Compile();
Func<float,uint> converter2 = x => (uint) x;
var aa = converter1(float.MaxValue); // == 2147483648
var bb = converter2(float.MaxValue); // == 0
}
}
同不同的行为可以为这个转换编译Expression.Convert
时,可以成立:这是一个ExpressionTrees错误?
Single -> UInt32
Single -> UInt64
Double -> UInt32
Double -> UInt64
看起来很奇怪,不是吗?
< ===添加使用DynamicMethod Visualizer和一些反映我的一些研究===>
我看了一下编译DynamicMethod
MSIL代码破解摆脱编译Expression<TDelegate>
DynamicMethod
:
Expression<Func<float, uint>> expr = x => (uint) x;
Func<float,uint> converter1 = expr.Compile();
Func<float,uint> converter2 = x => (uint) x;
// get RTDynamicMethod - compiled MethodInfo
var rtMethodInfo = converter1.Method.GetType();
// get the field with the reference
var ownerField = rtMethodInfo.GetField(
"m_owner", BindingFlags.NonPublic | BindingFlags.Instance);
// get the reference to the original DynamicMethod
var dynMethod = (DynamicMethod) ownerField.GetValue(converter1.Method);
// show me the MSIL
DynamicMethodVisualizer.Visualizer.Show(dynMethod);
而我得到的是这样的MSIL代码:
IL_0000: ldarg.1
IL_0001: conv.i4
IL_0002: ret
而且等于C#-compiled方法有此体:
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
不要任何人现在看到ExpressionTrees编译无效代码,这种转换?
Thx为您的答案,但是,重要的是,溢出行为是不同的!编译方法与纯代码有不同行为的原因是什么? – ControlFlow 2009-11-04 18:20:06
C#不使用'conv.u4' MSIL操作码来转换浮点值为无符号整数的其他技术=) – ControlFlow 2009-11-04 20:19:59