使用C#OpCodes发出返回对象的方法 [英] Using C# OpCodes to emit method that returns an object
问题描述
我正在创建一个动态类型,该类型具有一种我想返回一个对象的方法.我不明白如何实现这一目标.这是我到目前为止的内容:
I am creating a dynamic type which has a method that I'd like to return an object. I am failing to understand how to achieve this. Here's what I have so far:
// .. stuff to create type builder
MethodBuilder builder =
typeBuilder.DefineMethod(
method.Name,
MethodAttributes.Virtual | MethodAttributes.Public,
method.CallingConvention,
method.ReturnType,
typeArray1);
builder.InitLocals = true;
ILGenerator gen = builder.GetILGenerator();
Object myObjectIdLikeToReturn = someMethodCall();
//gen.??(??????????) // here's where I'm lost
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Ret);
我相信,如果我正确地读取了msdn,我需要在堆栈上获取myObjectIdLikeToReturn的引用-但是我还没有走运.谁能指出我正确的方向?
I believe, if I am reading the msdn correct, I need to get the reference of myObjectIdLikeToReturn on the stack--however I've not had luck. Can anyone point me in the right direction?
使其更加清晰.我正在尝试在IL中编写等效项:
To make it more clear. I'm attempting to write the equivalent in IL:
public virtual Object MyNewMethod() {
return myObjectIdLikeToReturn;
}
推荐答案
您有这行:
Object myObjectIdLikeToReturn = someMethodCall();
您说您希望将对myObjectIdLikeToReturn
的引用获取到堆栈中".但这是不可能的.我认为您混淆了这些事情发生的时间. IL生成代码类似于 compiling (编译)-一切都需要静态地了解.而myObjectIdLikeToReturn
是在生成代码时碰巧存在的变量,但对实际生成的类没有任何意义.您不能接受"对任意运行时对象的引用,这种想法根本没有任何意义.
You say you "want to get the reference to myObjectIdLikeToReturn
onto the stack." But that is impossible. I think you are confusing the timing of when these things are happening. The IL generation code is analogous to compiling -- everything needs to be known statically. Whereas myObjectIdLikeToReturn
is a variable that happens to exist while you are generating the code, but would not have any meaning to the class that is actually generated. You can't "bake in" a reference to some arbitrary runtime object, the idea simply doesn't make any sense.
您唯一的解决方案是以某种方式使您的IL执行对someMethodCall
的调用.但是,如果不了解该方法的用途以及它与生成的类型的关系,就很难详细说明如何实现该方法.
Your only solution is to somehow make your IL perform the invocation to someMethodCall
. But without knowing more about where that method lives and its connection to your generated type, it's hard to elaborate on precisely how you'll accomplish that.
这篇关于使用C#OpCodes发出返回对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!