c# - 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!
解决方案
我认为您在这里做出了错误的假设:
我正在尝试创建一个静态(因此非泛型)类
静态类绝对可以是通用的。我相信你只是想要:
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
静态类是一个非常奇怪的名称 - 听起来它应该是某些东西的基类,但没有任何东西可以从静态类派生。
其次,这只是一个美化的单例模式。我鼓励您研究依赖注入,而不是作为处理此类事情的更好方法。
推荐阅读
- laravel - 从 Laravel Horizon 中获取日志,在主管的 docker 中运行
- asp.net-core - 在 Startup.Configure 期间将自定义配置源添加到 ASP.NET Core
- r - 妊娠不识别数字变量
- excel - 将计数字段用作 Excel 数据透视表中的一行
- mysql - 为 MySQL 服务器指定主机名 - 连接被拒绝
- docker - 跟踪 Docker-for-mac CLI 程序执行输出以查找运行调用
- sql-server - 为什么在 docker-compose up 构建期间找不到 sqlcmd?
- python - 如何发送python套接字字节和字符串?
- javascript - React Router 参数无法与 tomcat 一起正常工作
- javascript - checkvalidity 没有检测到错误的值