gpt4 book ai didi

c# - 这是 ExpressionTrees 错误吗?

转载 作者:可可西里 更新时间:2023-11-01 08:43:19 25 4
gpt4 key购买 nike

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使用 DynamicMethod Visualizer 的 MSIL 代码 和一些反射 hack 得到 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 为这个转换编译了无效代码吗?

最佳答案

显然是一个错误,它在今天的 C# 4.0 版本中重现。感谢您提请我们注意。很有可能这个问题不会成为在最终版本之前修复的障碍;在这个后期阶段,我们只进行非常高优先级的修复,我们相信这些修复不会破坏发布的稳定性。更有可能的是,修复将使其成为 future 的服务版本;但当然,没有 promise 。

关于c# - 这是 ExpressionTrees 错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1674903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com