简体   繁体   中英

How to reset a readonly static property?

I'm using a third party open source Object Comparer util in a personal project through NuGet. The problem I have is that in the Context class there has a static read-only property( Default ) that I need to be able to modify:

    public class Context :
    IContext
{

    private static Context _default;
    public static Context Default {
        get {
            if( _default==null )
                _default = GetDefaultContext();

            return _default;

        }
    }

    private Guid _id;
    public Guid Id { get { return _id; } }


    internal static Context GetDefaultContext() {
        //....Initializing the context here, e.g. assign a GUID
        var ctx = new Context();
        _id = GetGuid();
    }

In my Compare method I call it like this:

var myContext = Context.Default;

The problem is that I need to initialize the Context (eg different GUIDS) for every Compare call. Something like:

var myContext = Context.GetDefaultContext();

But unfortunately GetDefaultContext is marked as internal so I have no public access to it.

My question is how can I get around this limitation without modifying the source code and get a different initialized Context each time with different GUID? Because the way it is now I'm always getting the same Context initialized in the beginning, with same GUID.

Here is the Source Code for Context ..

Since you know the name of the private field why not set it to null and make the original code do the work itself?

Context context = new Context ();
context.GetType().GetField("_default", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, null);

Now whenever you call the default property again it will call GetDefaultContext again.

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