Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 抛出验证异常的LINQ表达式_C#_Clr_Linq Expressions - Fatal编程技术网

C# 抛出验证异常的LINQ表达式

C# 抛出验证异常的LINQ表达式,c#,clr,linq-expressions,C#,Clr,Linq Expressions,为什么此代码抛出“System.Security.VerificationException:操作可能会破坏运行时的稳定性” MethodInfo mi=typeof(TypedReference).GetMethod(“InternalMakeTypedReference”,BindingFlags.NonPublic | BindingFlags.Static); ParameterExpression p1=表达式参数(typeof(IntPtr)); ParameterExpressio

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

MethodInfo mi=typeof(TypedReference).GetMethod(“InternalMakeTypedReference”,BindingFlags.NonPublic | BindingFlags.Static);
ParameterExpression p1=表达式参数(typeof(IntPtr));
ParameterExpression p2=表达式。参数(类型(对象));
ParameterExpression p3=表达式参数(typeof(IntPtr[]);
ParameterExpression p4=表达式.参数(typeof(Type));
Expression=Expression.Call(mi,Expression.Convert(p1,typeof(void*)),p2,p3,Expression.Convert(p4,Types.RuntimeType));
var m=Expression.Lambda(exp,p1,p2,p3,p4).Compile();
m(IntPtr.Zero,null,null,null);

由于参数错误,不会引发异常。

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

只需在表达式树中传递
IntPtr
就可以了,但如果参数是
void*
,这将没有帮助

一种可行的方法可能是使用直接生成方法access IL。默认情况下,它不能调用私有方法,但以下是解决该问题的答案:


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

谢谢,我将使用DynamicMethod解决方案。
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);