静态类作为实例属性

时间:2010-11-11 01:41:26

标签: c# architecture

我有一个基于接口的类,我希望有一些静态类作为属性。但是,我似乎无法找到一种方法来将静态类用作基于接口的类的实例属性。

public interface IHttpHelp
{
   ItemsManager {get;set;}
}

public static class ItemsManager
{
   //static methods
}

public class HttpHelper
{
   public ItemsManager { get { return ItemsManager;} 
}

上面的代码不起作用,因为“ItemsManager像变量一样使用,但它是一个类型错误。”反正以这种方式使用课程吗?

为了深入了解我正在做什么 - 我有一些静态帮助程序类可以访问httpruntime和当前上下文。我目前直接使用它们,但想进入一个将用于IoC的容器类。我可以让它们成为实例类而忘记它,但我想知道有没有办法解决这个问题。

3 个答案:

答案 0 :(得分:11)

您不能使用这样的静态类,因为根据定义,您无法创建它的实例,因此您无法从属性返回它。改为singleton

public class ItemsManager
{
    #region Singleton implementation

    // Make constructor private to avoid instantiation from the outside
    private ItemsManager()
    {
    }

    // Create unique instance
    private static readonly ItemsManager _instance = new ItemsManager();

    // Expose unique instance
    public static ItemsManager Instance
    {
        get { return _instance; }
    }

    #endregion

    // instance methods
    // ...
}

public class HttpHelper
{
    public ItemsManager ItemsManager { get { return ItemsManager.Instance; } }
}

答案 1 :(得分:0)

该语言不直接支持。您可以手动编写代理类,也可以使用Duck Typing Project之类的库在运行时发出代理类。

两者都将具有相同的结果:您将拥有一个实现该接口的类,并代理对静态类的静态方法的所有调用。无论您是想自己编写还是使用鸭子打字库,都取决于您。

编辑:如果您有这个选项,托马斯使用单身人士的答案将是可行的方法。

答案 2 :(得分:0)

静态类无法实现接口 - 它实际上没有多大意义。接口提供所有实例都支持的标准API,您可以通过标准接口交换实例并以多态方式访问方法。对于静态类,所有对它的引用都是通过类进行的。

通常在这种情况下,您希望工厂支持实现帮助程序的实例类的DI。

public interface IHttpHelper
{ }

public class RealHttpHelper
{ ... }

public class FakeHttpHelper 
{ ... }

public static class HttpHelper 
{
    public static IHttpHelper Instance
    {
        get 
        {
            return whatever ? new RealHttpHelper() : new FakeHttpHelper();
        }
    }
}

...
HttpHelper.Instance.Context...
...