首页 > 解决方案 > How can I use the same generic type in multiple methods in a non-generic static class

问题描述

I am trying to create a static (thus non-generic) class which contains a method called

Initialize<T>();

This method will be called on startup and will define the generic type of the class. So I want to be able to set the return value of other methods to the same type as T.

The result should look like something like this:

public static class ServiceClientBase
{
    private static IRestClient _client;

    public static void Initialize<T>(T restClient)
    {
        _client = restClient;
    }

    public static T GetClient()
    {
        return (T)_client;
    }
}

Obviously this doesnt work because GetClient() doesnt know type T. But T from GetClient should be equal to T from Initialize.

Is there a way to accomplish this? If not, is there a useful pattern, to accomplish something similar?

Thanks alot!

标签: c#generics

解决方案


我认为您在这里做出了错误的假设:

我正在尝试创建一个静态(因此非泛型)类

静态类绝对可以是通用的。我相信你只是想要:

public static class ServiceClientBase<T> where T : IRestClient
{
    private static T _client;

    public static void Initialize(T restClient)
    {
        _client = restClient;
    }

    public static T GetClient()
    {
        return _client;
    }
}

然后你会使用:

ServiceClientBase<Foo>.Initialize(client);
...
Foo foo = ServiceClientBase<Foo>.GetClient();

如果您使用两种不同的类型调用两次,您的非通用版本会导致问题Initialize- 您只有一个字段。使用泛型类型,每个构造类型都有一个字段。

作为旁注,ServiceClientBase静态类是一个非常奇怪的名称 - 听起来它应该是某些东西的类,但没有任何东西可以从静态类派生。

其次,这只是一个美化的单例模式。我鼓励您研究依赖注入,而不是作为处理此类事情的更好方法。


推荐阅读