问题
I have an old .NET DLL which I have lost the source code to and I wanted to see if I could change its behavior.
It has a method that takes in a string and returns a string.
I would want to rewrite this method such that I can return
startStr + " test";
I tried .NET reflector but the project it produced has a bunch of strange errors so I cannot recompile it.
I then tried Reflexil, but it only offers assembly level changes.
Is there any way I could rewrite the method in C# and have the DLL use my method instead?
回答1:
Reflexil should be able to handle this for you - you need to switch to IL view in Reflector and then you can go to the method that you want to change, pull up Reflexil and make your changes. This avoids the problems with decompiling the assembly to source code (which never worked for me without errors in Reflector).
If all you want to do is append a string to a string variable, you can just do something like:
// assuming your original string is already on the stack
ldstr " test"
call System.String System.String::Concat ( System.String, System.String )
This will create a new string on the stack with test
appended to it. Once you're done with the editing, you can save the assembly back to disk.
If you need something more complicated (like appending a string returned by a function call), you simply need to call the right method and then call Concat()
on the two strings on the stack.
If your original method returns a string then wrapping it in a new function in a new assembly may be a better solution, though. I'd only edit the IL if you really need the original assembly to change because - for example - the string returned from the particular method is used within that same assembly and you need other functions in that assembly to see the changed return value.
Note: I used Reflector 6.8.2.5 and Reflexil 1.0 for this - current Reflector / Reflexil may be different. Let me know if you need these files for your changes.
回答2:
Have you tried extension methods? Simply add another method to an existing class.
You do this by:
public static class Foo {
public static String SomeMethod (this Bar bar) {
return bar.OriginalMethod()+" test";
}
}
If the original class was Bar
.
回答3:
I've never used .NET reflector, but you can try using the free decompiler offered by JetBrains, the makers of ReSharper, it has never failed me. http://www.jetbrains.com/decompiler/
On a side note, since you say that the dll is very old, couldn't the compilation errors in the Reflector generated project be produced by different versions of references or targeted framework?
来源:https://stackoverflow.com/questions/19215670/rewrite-a-method-of-a-net-dll