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

C# 在C中强制实现全局可访问类#,c#,C#,在我的项目中,我需要一个全局可访问的类(比如静态类)。但是,我希望我的代码强制我的库的用户在每次使用它时实现它。有没有办法在C#中实现这一点 上述代码将在所有库类中使用,但细节会改变其他类的响应方式。我希望用户决定如何配置库,即编写自己的全局配置类 你似乎想要一个普通的单身汉。想想这样的事情: public class Singleton<T> where T: ISomething, class, new() { // not thread-safe, don't thin

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


上述代码将在所有库类中使用,但细节会改变其他类的响应方式。我希望用户决定如何配置库,即编写自己的全局配置类

你似乎想要一个普通的单身汉。想想这样的事情:

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

通过要求类的一个实例被传递到你的库来强制它,通过一个接口来实现它。“每次他/她使用它时都实现它”是什么意思?他们每次都需要上新课吗?你到底想实现什么?@LasseVågsætherKarlsen问题是静态类不实现接口。@CamiloTerevinto我希望该类在我的项目中全局可用,我不希望每次使用时都实例化它。同时,我想让用户配置它的详细信息。如果它是一个静态类,如何使用库来进一步实现它?您能用一些示例代码解释一下您的问题吗?为什么要在类签名中添加“new()”关键字?在这种情况下这是必须的吗?@aspdev它是必须的,以便能够创建该类的新实例。否则,您需要一个接受ObjectDependecy注入的构造函数,该注入是否适用于您的解决方案?我的意思是,我能在需要T的地方注入一个特定的对象吗?@aspdev不,DI基本上与单例相反。您的问题与DI需求相反
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();
}
public void INeedTheSingleton<T>(Singleton<T> instance) where T: ISomething, class, new()
{
    instance.DoSomething();
}