gpt4 book ai didi

c# - LINQ 表达式抛出 VerificationException

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:38 25 4
gpt4 key购买 nike

为什么此代码会抛出“System.Security.VerificationException:操作可能会破坏运行时的稳定性。”?

MethodInfo mi = typeof(TypedReference).GetMethod("InternalMakeTypedReference", BindingFlags.NonPublic | BindingFlags.Static);
ParameterExpression p1 = Expression.Parameter(typeof(IntPtr));
ParameterExpression p2 = Expression.Parameter(typeof(object));
ParameterExpression p3 = Expression.Parameter(typeof(IntPtr[]));
ParameterExpression p4 = Expression.Parameter(typeof(Type));
Expression exp = Expression.Call(mi, Expression.Convert(p1, typeof(void*)), p2, p3, Expression.Convert(p4, Types.RuntimeType));
var m = Expression.Lambda<Action<IntPtr,object,IntPtr[],Type>>(exp, p1, p2, p3, p4).Compile();
m(IntPtr.Zero,null,null,null);

由于参数错误,没有抛出异常。

最佳答案

据我所知,您不能构建包含不安全代码的表达式树。不安全代码意味着无法验证类型/内存安全,但根据 this error description表达式只有在其代码可验证时才能被编译。

在表达式树中传递 IntPtr 应该没问题,但如果参数是 void*,那将无济于事。

一个可行的方法可能是使用 Reflection.Emit直接生成方法访问 IL。默认情况下它不能调用私有(private)方法,但这是解决该问题的答案:https://stackoverflow.com/a/1778446/1659828

无论如何,在您的情况下,我不知道您要完成什么,但尝试使用不符合 CLS 的 API 的实现细节似乎可能有更好的方法。

关于c# - LINQ 表达式抛出 VerificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27463129/

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