Override dll class property set

十年热恋 提交于 2019-12-22 08:47:26

问题


I'm using a thousand instances of a closed DllClass in my project.

public sealed class DllClass 
{
    public DllClass();
    public string DllClassProperty {get; set;}
}

DllClassProperty set is used a thousand of times and I need to override the value set if a parameter is set on Web.config.

I found this Interface INotifyPropertyChanged, but I can't use it, because I don't have access to the class and I can't extend it.

I'm thinking, if there's a way to do something like this, but I think this is not possible in C#:

public class OnSetPropertyListener<DllClass>
{
    public void OnSetProperty(PropertyInfo propertyInfo, DllClass instance) 
    {
        // set another value, for example: "new value"
    }
}

How can I override the value set in DllClassProperty? Is it possible?


回答1:


Surprisingly, there is a way to solve your problem. It's not pretty, but it satisfies the constraints of your question.

Step 1: Create a wrapper around DllClass, i.e. a new class MyDllClassWrapper, which behaves exactly like DllClass except for the change that you want to implement. This is usually done by rebuilding the public interface of DllClass and just forwarding all operations to a private DllClass instance.

Now you just need to use MyDllClassWrapper everywhere where you currently use DllClass. You mentioned in the comments that you don't want to change all those calls, so let's automate that:

Step 2: Use Substitute.Fody to automatically replace all references to DllClass by references to MyDllClassWrapper in a post-compile step:

[assembly: Substitute(typeof(DllClass), typeof(MyDllClassWrapper))]

Note, though, that everyone reading your code will be thoroughly confused, since the source code points to DllClass, but MyDllClassWrapper is used instead. Thus, I recommend that you use this technique only as a temporary workaround until you find the time to cleanly replace all references to DllClass with references to MyDllClassWrapper.



来源:https://stackoverflow.com/questions/48460584/override-dll-class-property-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!