如何重置只读静态属性?

时间:2014-05-21 16:28:24

标签: c# .net static

我通过NuGet在个人项目中使用第三方开源Object Comparer util。我遇到的问题是在Context类中有一个我需要能够修改的静态只读属性(Default):

    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();
    }

在我的Compare方法中,我称之为:

var myContext = Context.Default;

问题是我需要为每个Context电话初始化Compare(例如,不同的GUIDS)。 类似的东西:

var myContext = Context.GetDefaultContext();

但不幸的是GetDefaultContext被标记为内部,所以我没有公开访问它。

我的问题是如何在不修改源代码的情况下解决此限制,并且每次使用不同的GUID获得不同的初始化Context?因为它现在的方式我总是在开头使用相同的GUID初始化相同的Context。

这是Source Code for Context ..

1 个答案:

答案 0 :(得分:1)

既然您知道私有字段的名称,为什么不将其设置为null并使原始代码自行完成工作呢?

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

现在,无论何时再次调用默认属性,它都会再次调用GetDefaultContext

相关问题