在C#中强制实施可全局访问的类

时间:2018-12-01 14:22:26

标签: c#

我的项目中需要一个可全局访问的类(例如静态类)。但是,我希望我的代码强制我的库用户在每次使用它时都实施它。有没有一种方法可以在C#中实现?

public static class Config
{
  // config details for the library 
}

以上代码将在所有库类中使用,但是详细信息会更改其他类的响应方式。我希望用户决定如何配置库,即编写他或她自己的全局Config类。

1 个答案:

答案 0 :(得分:0)

似乎您想要类似通用单例的东西。想像这样的东西:

public class Singleton<T> where T: ISomething, class, new()
{
    // not thread-safe, don't think it matters for this example
    private static Singleton<T> _instance = new T();
    public static Singleton<T> Instance => _instance;
}

public interface ISomething
{
    void DoSomething();
}

这种方式:

  1. 您拥有该类的唯一实例,可以通过Singleton<Something>.Instance
  2. 访问
  3. 您强制库的客户端使用您想要实现的版本来实现自己的ISomething版本。

然后您可以将该类用作所需类的要求:

public void INeedTheSingleton<T>(Singleton<T> instance) where T: ISomething, class, new()
{
    instance.DoSomething();
}
相关问题