[英]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. 因此,我希望能够将其他方法的返回值设置为与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. 显然这不起作用,因为GetClient()不知道类型T。但是GetClient中的T应该等于Initialize中的T。
Is there a way to accomplish this? 有没有办法做到这一点? If not, is there a useful pattern, to accomplish something similar? 如果不是,是否有有用的模式来完成类似的任务?
Thanks alot! 非常感谢!
I think you've made an incorrect assumption here: 我认为您在这里做出了错误的假设:
I am trying to create a static (thus non-generic) class 我正在尝试创建一个静态(因此是非通用的)类
Static classes can absolutely be generic. 静态类可以绝对是泛型的。 I believe you just want: 我相信您只想要:
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;
}
}
Then you'd use: 然后,您将使用:
ServiceClientBase<Foo>.Initialize(client);
...
Foo foo = ServiceClientBase<Foo>.GetClient();
Your non-generic version would cause problems if you called Initialize
twice with two different types - you've only got a single field. 如果您使用两种不同的类型两次调用了Initialize
则非通用版本会导致问题-您只有一个字段。 With the generic type, you've got a field per constructed type. 使用泛型类型时,每个构造类型都有一个字段。
As a side-note, ServiceClientBase
is a very odd name for a static class - it sounds like it should be the base class for something, but nothing can derive from a static class. 附带说明一下, ServiceClientBase
是静态类的一个非常奇怪的名称-听起来它应该是某些东西的基类,但是静态类不能派生任何东西。
Secondly, this is just a glorified singleton pattern. 其次,这只是一个光荣的单例模式。 I'd encourage you to investigate dependency injection instead as a better way of handling this sort of thing. 我鼓励您研究依赖注入作为一种更好的方式来处理这种事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.