开发者

Best practise for overriding static classes

开发者 https://www.devze.com 2022-12-31 07:01 出处:网络
As it is not possible to override a static class in c#, if i wan开发者_Go百科t to override a method I generally define a delegate matching the signature of the static method, then modify the method al

As it is not possible to override a static class in c#, if i wan开发者_Go百科t to override a method I generally define a delegate matching the signature of the static method, then modify the method along the lines of:

public static void foo(int bar)
{
  if (delegatename!=null)
  {
   delegatename.Invoke(bar);
  }
  else
  {
   //execute previous code as normal
  }
}

I feel a twinge of guilt, knowing this is a bit messy.

Can anyone suggest a neater solution to this problem (other than rewriting the original structure)


It seems that you are using the static class as a way to provide a single access point to some resource in your application. If it is the case, you should consider to use an implementation of Singleton design pattern. Doing it, you could take advantage of use inheritance on your non-static classes.

public abstract class Base { ... }

public class Impl : Base { ... }

public class Singleton : Impl
{ 
    #region Static Members

    static readonly Singleton _instance = new Singleton(); 

    static Singleton() { } 

    static public Singleton Instance 
    { 
        get  { return _instance; } 
    } 

    #endregion Static Members

    #region Instance Members

    private Singleton() { } 

    // Method overrides goes here...

    #endregion Instance Members
} 

A deeper discussion on how to implement the singleton design pattern on C# can be found on Implementing the Singleton Pattern in C# article.


Consider using dependency injection, as static singletons make test isolation essentially impossible and re-usability extremely painful.

Singletons are cool, just don't do it using statics. There are many resources on "dependency injection," which Google can easily find for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消