gpt4 book ai didi

.net - 是否可以从 .NET 中的动态方法调用内部方法?

转载 作者:行者123 更新时间:2023-12-02 19:41:18 25 4
gpt4 key购买 nike

我正在尝试从动态生成的方法中调用内部方法。 il代码很简单:ldarg_0、callvirt、ret。

执行该方法失败,并出现 TypeLoadException,表示无法加载定义内部方法的类型。

当我想到这一点时,这似乎是合乎逻辑的,因为动态方法宿主程序集不是该方法的声明类型程序集的友元。

但是,我预计动态方法仍然可以工作,就像 Delegate.CreateDelegate 一样。毕竟我确实拿到了内部方法的MethodInfo,所以权限障碍已经过去了。

无论如何,问题是“是否可以从动态生成的方法调用内部方法?”

谢谢。

编辑:

这是一个演示该问题的简单代码示例:

using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;

namespace A
{
internal class Data
{
internal string String { get; set; }
}

public static class Program
{
public static void Main()
{
Expression<Func<Data, string>> expr = x => x.String;
var getterInfo = ((PropertyInfo)((MemberExpression)expr.Body).Member).GetGetMethod(true);
var getter1 = (Func<Data, string>)Delegate.CreateDelegate(typeof(Func<Data, string>), getterInfo);
var dm = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object) });
var gen = dm.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Castclass, typeof(Data));
gen.Emit(OpCodes.Callvirt, getterInfo);
gen.Emit(OpCodes.Ret);
var getter2 = (Func<object, object>)dm.CreateDelegate(typeof(Func<object, object>));

var data = new Data() { String = "Hello" };
var str1 = getter1(data);
var str2 = getter2(data);
}
}
}

在代码中,我创建了两个打开的实例委托(delegate)来访问 Data.String 实例属性:

  • 使用 Delegate.CreateDelegate 类型安全 getter1
  • 使用 DynamicMethod 键入不安全的 getter2

由 Delegate.CreateDelegate 创建的类型安全委托(delegate)可以工作,而使用 DynamicMethod 创建的类型安全委托(delegate)则失败并出现 TypeLoadException。

请注意,我不希望采用类型安全的方法,因为创建 getter 的上下文不是通用的。当然,我可以解决这个问题,但现在的问题是主体 - 为什么 DynamicMethod 失败而 Delegate.CreateDelegate 成功?

最佳答案

如果您跳过可见性检查,它将起作用。

更改此行

var dm = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object) }, true);

参见msdn :(特别是包含所有规则的表格。)

这是来自构造函数的 doco。

restrictedSkipVisibility Type: System.Boolean true to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method, with this restriction: the trust level of the assemblies that contain those types and members must be equal to or less than the trust level of the call stack that emits the dynamic method; otherwise, false.

关于.net - 是否可以从 .NET 中的动态方法调用内部方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1777918/

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