Static Instance Base/Derived class

自古美人都是妖i 提交于 2019-12-05 06:07:06

Not sure if I understand your question correctly, but I would do it like this:

public class ResourceInstance<T>
    where T : ResourceInstance<T> // To ensure correct usage
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance != null)
                return _instance;

            var name = typeof(T).Name;
            _instance = (T)Application.Current.TryFindResource(name);

            return _instance;
        }
    }
}

public class FooConverter : ResourceInstance<FooConverter>, IValueConverter
{
    ...
}

The constraint on T ensures that the class will be used with the pattern class X : ResourceInstance<X>; this way, typeof(X) will always be X.

I believe there is a slight fallacy in your code. Imagine if you have:

SomeConverter : BaseConverter { ... }
SomeOtherConverter : BaseConverter { ... }

then both SomeConverter.Instance and SomeOtherConverter.Instance would be the same object (i.e. ResourceInstance<IValueConverter>.Instance) - set only once (whichever was called first), which is probably not what you've intended to have.

How about the following? Slightly less compact, but a. resolves the problem above and b. works :)

public abstract class ResourceInstance<TBase, TActual>
{
   private static TBase _instance;
   public static TBase Instance
   {
       get
       {
           if (_instance == null)
              _instance = (T)Application.Current.TryFindResource(typeof(TActual).Name);

           return _instance;
       }
   }
}

and then declare your types as

SomeConverter : ResourceInstance<IValueConverter, SomeConverter>, IValueConverter { ... }

(I've omitted BaseConverter as it probably has little purpose given this implementation).

static members are entirely specific to the declaring class; subclasses do not get separate copies. The only exception here is generics; if an open generic type declares static fields, the field is specific to that exact combination of type arguments that make up the closed generic type; i.e. Foo would have separate static fields to Foo, assuming the fields are defined on Foo.

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