I've done this before, so I know it can be done..(although badly documented) but forgot how. I've been searching for 2 hours now and can't find anything like it.
I want to push and pull values on the callstack, like so:
public void Method1()
{
InsertMagicClassHere.Push("Key", 1);//or something
Method2();
}
public void Method2()
{
int value = InsertMagicClassHere.Pull("Key");//or something
}
I need this parameter in nearly all my methods for logging.. and don't want to pass this 3 layers deep with arguments.
You are looking for Reflection.Emit; however, this is not how it works.
You can't really emit inline opcodes.
Instead, you can emit whole methods/classes and load them as 'temporary' assemblies. You then call into the emitted method.
Obligatory sample:
public void CreateMethod()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
AssemblyBuilder asmbuilder = this.GetAssemblyBuilder("MyAssembly");
ModuleBuilder mbuilder = this.GetModule(asmbuilder);
TypeBuilder tbuilder = this.GetTypeBuilder(mbuilder, "MyClass");
Type[] tparams = { typeof(System.Int32), typeof(System.Int32) };
MethodBuilder methodSum = this.GetMethod(tbuilder, "Sum", typeof(System.Single),
tparams);
ILGenerator generator = methodSum.GetILGenerator();
generator.DeclareLocal(typeof(System.Single));
generator.Emit(OpCodes.Ldarg_1);
generator.Emit(OpCodes.Ldarg_2);
generator.Emit(OpCodes.Add_Ovf);
generator.Emit(OpCodes.Conv_R4);
generator.Emit(OpCodes.Stloc_0);
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Ret);
}
So what you could do
See these articles for good starters:
Okay. the answer is:
CallContext
This works:
public void Method1()
{
CallContext.SetData("Key", 1);
Method2();
}
public void Method2()
{
int value = (int)CallContext.GetData("Key");
}
Like I said this is not a well known feature.. If you knew it, you would have known what I was referring to.
I think it's a cool feature, not many uses for it, but still..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With