简体   繁体   中英

How to Override a C# method in existing DLL?

I have an instance where I am using someone else's library, imported as a DLL. I just want to change only two private functions in that class. I really like to do this externally to the DLL, so when that other person releases a new DLL, I can just quickly update my DLL, and not have to alter the source and build my own DLL.

Is it possible to do this? Can I somehow override a few private functions in C# dll externally from the DLL?

I really like to do this externally to the DLL, so when that other person releases a new DLL, I can just quickly update my DLL

Think about this. Let's say you successfully intercept/override their private functions. What will happen when the next release removes those functions or changes their behavior?

Members are usually private for a reason.

Valid approaches are to wrap the external assembly to control/abstract behavior, or to override public/protected members that are designed for inheritance.

Calling private members is easy with reflection. Modifying them so that their callers use a new implementation is more complex.

and not have to alter the source and build my own DLL.

If you really, really need to do this, altering the source is probably the most straightforward approach.* You could also look at IL weaving which might be appropriate for this task.

A better approach would be to work with the author to make the library more extensible in the areas that you require.

* This assumes you have legitimate access to the source or are allowed to decompile the assembly. This could violate a reverse engineering clause in a license, invalidate a maintenance contract, etc. I am not a lawyer.

I think you can use TypeBuilder.DefineMethodOverride. See this question for details Is there a way to "override" a method with reflection? .

If this doesn't work, you can try to build a runtime proxy class also using reflection but replacing calls to methods you want to override with your implementations. That's of course is a little bit of voodoo. Code instrumentation does similar things -- injecting custom code into your methods. In fact that's what I suggest researching -- how instrumentation works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM