.net - 如何使用 Mono.Cecil 重新抛出来替换 ILAsm 抛出?

标签 .net powershell mono.cecil ilasm

我有一个 C# dll,其成员类似于以下内容:

public void DoStuff(int i) {
    try {
        something.InnerDoStuff(i);
    }
    catch (Exception ex) {
        throw ex;
    }
}

我想出了如何获取throw opcode :

Add-Type -Path 'c:\Program Files\ILSpy2\Mono.Cecil.dll'
Add-Type -Path 'c:\Program Files\ILSpy2\Mono.Cecil.pdb.dll'

$dll = 'c:\Program Files\ZippySoft\Something\foo.dll'
$assemblyDefinition = [Mono.Cecil.AssemblyDefinition]::ReadAssembly($dll);

$doThingsIlAsm = (
    (
        $assemblyDefinition.MainModule.Types `
            | where { $_.Name -eq 'DoerOfThings' } `
            | select -first 1 *
    ).Methods | where { $_.Name -eq 'DoStuff' }
).Body.Instructions 

$throwOp = ($doThingsIlAsm | where {
    $_.OpCode.Name -eq 'throw'
})

我的问题是如何用 rethrow opcode 替换 throw 操作码?

最佳答案

我相信您可以获得ILProcessor对于你的方法,Create rethrow 操作码,然后使用处理器的 Replace方法将 throw 替换为 rethrow

不要立即获取方法主体的指令,而是获取对方法主体的引用并使用它来获取 myMethod.Body.GetIlProcessor 以及 myMethod.Body.Instructions。然后你就可以找到原来的 throw 指令,并使用 Replace 方法将它们交换出来。

这还没有经过测试,但我认为其要点是:

$throw = # your existing stuff
$il = myMethod.Body.GetIlProcessor()
$rethrow = $il.Create(OpCodes.Rethrow) # not sure about the powershell syntax for enums
$il.Replace($throw, $rethrow)

关于.net - 如何使用 Mono.Cecil 重新抛出来替换 ILAsm 抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12096164/

相关文章:

c# - 在 Powershell 中获取登录用户

c# - 使用 Mono.Cecil 的 .NET 程序集的目标架构

c# - 在 "undefined"变量上拆分字符串

powershell - "-"在 Powershell 中做什么

powershell - 将Format-Hex PowerShell表转换为原始十六进制转储

c# - 替换方法的 MethodBody 中的指令

c# - (C#) 如何使用Mono.Cecil判断是否是枚举类型?

c# - 数据访问层c#的单元测试

c# - .NET throttle 算法

c# - 为什么在添加到集合时不为所有对象调用 Equals()