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
对于此次转化:
Single -> UInt32
Single -> UInt64
Double -> UInt32
Double -> UInt64
看起来很奇怪,不是吗?
<===添加了一些我的研究===>
我看了编译 DynamicMethod
使用MSIL代码 DynamicMethod Visualizer 和一些反思黑客得到 DynamicMethod
来自编译 Expression<TDelegate>
:
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#编译方法有这个主体:
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
现在有人看到ExpressionTrees编译这个转换的无效代码吗?