正如主题所说,我正在向程序集中注入一些代码。我想得到类似的东西:
string str;
int num;
switch (choice)
{
case 1:
str = "b "; num = 2; break;
default:
str = "a "; num = 1; break;
}
if(num == 1) {str += "a";}
else if(num == 2) {str += "b";}
我设法注入了switch语句,如果部分成功的话。我写的代码如下:
switches[0] = worker.Create(OpCodes.Ldstr, "a ");
switches[1] = worker.Create(OpCodes.Ldstr, "b ");
Instruction ifStart1 = worker.Create(OpCodes.Ldc_I4, 1);
Instruction ifStart2 = worker.Create(OpCodes.Ldc_I4, 2);
Instruction ifEnd = worker.Create(OpCodes.Ldloc, returnString);
listInstr.Add(worker.Create(OpCodes.Ldstr, ""));
listInstr.Add(worker.Create(OpCodes.Stloc, returnString));
listInstr.Add(worker.Create(OpCodes.Ldc_I4, 0));
listInstr.Add(worker.Create(OpCodes.Stloc, helpInt));
listInstr.Add(worker.Create(OpCodes.Ldarg, choice));
listInstr.Add(worker.Create(OpCodes.Switch, switches));
listInstr.Add(switches[0]);
listInstr.Add(worker.Create(OpCodes.Stloc, returnString));
listInstr.Add(worker.Create(OpCodes.Ldc_I4, 1));
listInstr.Add(worker.Create(OpCodes.Stloc, helpInt));
listInstr.Add(worker.Create(OpCodes.Br, ifStart1));
listInstr.Add(switches[1]);
listInstr.Add(worker.Create(OpCodes.Stloc, returnString));
listInstr.Add(worker.Create(OpCodes.Ldc_I4, 2));
listInstr.Add(worker.Create(OpCodes.Stloc, helpInt));
listInstr.Add(worker.Create(OpCodes.Br, ifStart1));
//if 1
listInstr.Add(ifStart1);
listInstr.Add(worker.Create(OpCodes.Ldloc,helpInt));
listInstr.Add(worker.Create(OpCodes.Bne_Un, ifEnd));
listInstr.Add(worker.Create(OpCodes.Ldloc, returnString));
listInstr.Add(worker.Create(OpCodes.Ldstr, "a"));
listInstr.Add(worker.Create(OpCodes.Call, concat));
listInstr.Add(worker.Create(OpCodes.Stloc, returnString));
// if 2
listInstr.Add(ifStart2);
listInstr.Add(worker.Create(OpCodes.Ldloc, helpInt));
listInstr.Add(worker.Create(OpCodes.Bne_Un, ifEnd));
listInstr.Add(worker.Create(OpCodes.Ldloc, returnString));
listInstr.Add(worker.Create(OpCodes.Ldstr, "b"));
listInstr.Add(worker.Create(OpCodes.Call, concat));
listInstr.Add(worker.Create(OpCodes.Stloc, returnString));
listInstr.Add(ifEnd);
listInstr.Add(worker.Create(OpCodes.Ret));
不幸的是,它在反编译器中生成嵌套ifs。我尝试添加操作码Ret指令(正如我在一些网站上看到的那样),但它混淆了反编译器,它无法生成代码。我不知道我应该使用哪些操作码,或者如何将if语句用作我之前给出的示例。有没有办法改进我的代码?