Reputation: 115
I want to make a DynamicMethod which in turn behave like the following for example:
AnyClass myClass = new AnyClass();
Func<AnyClass> myFunc = () => myClass;
I know that when I want to make it work with an int
instead of AnyClass
I have to use the following snippet to return every time the number 12:
// Define method
DynamicMethod method = new DynamicMethod(
"Name",
typeof(int),
new Type[] { });
// Define method body
ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Ldc_I4, 12);
il.Emit(OpCodes.Ret);
But now I ask myself how to do it with a not build-in class.
Edit:
At the end I want to get a reference from a local variable when I call the DynamicMethod. Look at the following snippet to better understand what I wanted to archieve. Here I want a func which returns on every call the variable I passed to the function which creates the func.
Func<AnyClass> GetMethodWithAFunc(AnyClass myClass) {
Func<AnyClass> myFunc = () => myClass;
return myFunc;
}
The generated IL Code for the snippet can be found on SharpLab. Unfortunately we have to provide a context where the data to return in the DynamicMethod could be saved. Finally I suggest a static cache and to use converting and unboxing when returning the values.
Upvotes: 0
Views: 323