我正在通过在运行时使用 Reflection.Emit
创建自己的函数来学习 CIL。实际上,我很惊讶到目前为止事情是多么容易,但我遇到了一些我无法猜测的事情,而且我在文档中找不到任何相关内容。
我正在尝试创建一个函数,它只打印我定义的一个非常简单的类。例如,如果我更改我的代码以打印 string
,它可以工作,但当我传递我的类 A
的实例时它总是无法运行。
奇怪的是,我可以注释掉我的函数体,它仍然失败并返回 TargetInvocationException
。它一定很简单,但我看不出发生了什么!
class A
{
public override string ToString()
{
return "AAA!";
}
}
class Program
{
static void Main(string[] args)
{
DynamicMethod func = new DynamicMethod("func", null, new Type[] { typeof(A) });
ILGenerator il = func.GetILGenerator();
//il.Emit(OpCodes.Ldarg_0);
//il.Emit(OpCodes.Box, typeof(A));
//il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(A) }));
il.Emit(OpCodes.Ret);
func.Invoke(null, new object[] { new A() });
Console.Read();
}
}
我做错了什么导致抛出异常?为什么这只发生在我的类(class)中?
最佳答案
实际上这很愚蠢。我在这上面花了几个小时,但是当我听从 Laurent Etiemble 的建议并创建了一个委托(delegate)时,我得到的异常告诉我我的 A 类不是公开的。
解决方案:在class A
前加上public关键字。完美运行。我知道它必须非常简单。
关于c# - 为什么用我自己的类的实例调用 DynamicMethod 会导致异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2225091/