Reflection.Emit 动态创建方法

发布于 2024-08-03 19:27:00 字数 627 浏览 1 评论 0原文

我想动态创建一些方法,该方法将接受单个参数 - 类 A 的实例,然后在传递的 A 实例中执行方法 B。B 具有 int 类型的参数。所以这是架构:

dynamicMethod(A a){
a.B(12);
}

这是我尝试过的:

DynamicMethod method = new DynamicMethod(string.Empty, typeof(void), new[] { typeof(A) }, typeof(Program));
MethodInfo methodB = typeof(A).GetMethod("B", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
ILGenerator gen = method.GetILGenerator();

gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_S, 100);
gen.Emit(OpCodes.Call, methodB);

但编译器告诉我 CLR 没有找到该方法。你能帮我吗?

I'd like to create dynamically some method, which will accept single parameter - instance of class A and then will execute method B in passed instance of A. B has parameter of type int. So here is the schema:

dynamicMethod(A a){
a.B(12);
}

Here what I tried:

DynamicMethod method = new DynamicMethod(string.Empty, typeof(void), new[] { typeof(A) }, typeof(Program));
MethodInfo methodB = typeof(A).GetMethod("B", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
ILGenerator gen = method.GetILGenerator();

gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_S, 100);
gen.Emit(OpCodes.Call, methodB);

But compiler tells me that CLR doesn't found the method. Could you help me with it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月亮邮递员 2024-08-10 19:27:00

MSDN 关于Type.GetMethod 函数的类型参数

Type 对象数组,表示要获取的方法的参数的数量、顺序和类型。

您传递一个空数组,表示“不带参数的方法”。但正如你所说“B 有一个 int 类型的参数。”

这会起作用:

MethodInfo methodB = typeof(A).GetMethod(
            "B",
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
            null,
            new Type[] { typeof(int) }
            , null);

如果我理解正确 Ldarg_S 将加载方法的第一百个参数,类似于 Ldarg_0:

gen.Emit(OpCodes.Ldarg_S, 100);

要加载常量值,请使用 Ldc_I4

gen.Emit(OpCodes.Ldc_I4, 100);

MSDN about the types parameter of the Type.GetMethod function:

An array of Type objects representing the number, order, and type of the parameters for the method to get.

You pass an empty array which indicates "a method that takes no parameters". But as you said "B has [a] parameter of type int."

This will work:

MethodInfo methodB = typeof(A).GetMethod(
            "B",
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
            null,
            new Type[] { typeof(int) }
            , null);

If I understand correctly Ldarg_S will load the one hundredth argument of your method, similiarly to Ldarg_0:

gen.Emit(OpCodes.Ldarg_S, 100);

For loading a constant value use Ldc_I4

gen.Emit(OpCodes.Ldc_I4, 100);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文