静态参数化类中关于其实例会发生什么?
假设我有这个类:
public class DispatcherService<T>
{
private static Action<T> Dispatcher;
public static void SetDispatcher(Action<T> action)
{
Dispatcher = action;
}
public static void Dispatch(T obj)
{
Dispatcher.Invoke(obj);
}
}
让我说清楚......对于每种类型,我只有一个 DispatcherService
实例,并且仅在我调用它时。正确的?
只是询问内存问题。
Suppose I have this class:
public class DispatcherService<T>
{
private static Action<T> Dispatcher;
public static void SetDispatcher(Action<T> action)
{
Dispatcher = action;
}
public static void Dispatch(T obj)
{
Dispatcher.Invoke(obj);
}
}
Let me get this straight... I'll have only one instance of DispatcherService<T>
for each type, and only when I call it. Right?
Just asking for memory issues.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是。
是的。
该代码由 CLR 在需要使用时发出。
请注意
,如果我在你那里,我会将其更改为单例。
Yes.
Yes.
The code is emitted by CLR when it needs to use it.
Note
if I where you I would change it to singleton.
您可以拥有任意数量的 DispatcherService 实例,因为该类可以自由实例化。另一件事是没有意义,因为它没有实例方法。如果不打算实例化它,您可以将其更改为
public static class DispatcherService
,如此例所示。对于每种类型,您最多还有一个
DispatcherService.Dispatcher
实例,这正是您可能想知道的。如果您不访问特定T
的DispatcherService
,则不会为该T
分配任何资源。You can have as many instances of
DispatcherService
as you like, since the class can be instantiated freely. It's another matter that there's no point to that because it has no instance methods. You can change it topublic static class DispatcherService<T>
if it's not meant to be instantiated, as in this example.You will also have at most one instance of
DispatcherService.Dispatcher
for each type, which is what you probably want to know. If you don't accessDispatcherService
for a specificT
, no resources will be allocated for thatT
.