抽象超类中的c# static将在子类之间共享吗?
我正在编写一些连接到模拟服务的 ashx 处理程序,我希望它们共享模拟服务实例。我最简单的方法是创建一个静态实例
public class AbstractHandler
{
static IService _impl;
public static IService Impl
{
get
{
if (_impl == null)
{
_impl = new MockService();
}
return _impl;
}
}
}
但是,我想知道这是否会起作用;从此类继承的不同处理程序将拥有自己的 static _impl 引用还是将共享?
i'm writing some ashx handlers which are wired to a mock service, and i want them to share the mock service instance. The simplest approach i though was creating a static instance
public class AbstractHandler
{
static IService _impl;
public static IService Impl
{
get
{
if (_impl == null)
{
_impl = new MockService();
}
return _impl;
}
}
}
However, i'm wondering if this is going to work at all; will different handlers that inherit from this class will have their own static _impl reference or they will be shared?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
静态字段存在一次,但在泛型类型的情况下除外,在这种情况下,对于每个使用的泛型参数组合,静态字段都存在一次。
即使该类是基类(可能是抽象类),也适用相同的规则。请注意,如果声明该字段的类不是通用的,则该字段将存在一次,即使后代是通用的。仅当声明静态字段的类是通用的时,有关“每个组合一次...”的规则才起作用。
所以,如果你的问题是:
那么答案是您应该使基类通用,并将后代类型作为通用参数传递。
示例 LINQPad 脚本演示“每个通用参数组合一次”:
输出:
使用基类演示的示例:
输出:
A static field exists once, except in the case of a generic type, in which case it exists once for each used combination of generic parameters.
Even if the class is a base class, possibly abstract, the same rules apply. Note that if the class in which the field is declared is not generic, the field will exist once, even if descendants are generic. The rule about "once per combination ..." only comes into play if the class that declares the static field is generic.
So, if your question instead had been:
Then the answer would've been that you should make your base class generic, and pass the descendant type as the generic parameter.
Example LINQPad script to demonstrate the "once per generic parameter combination":
Output:
Example to demonstrate with base class:
Output: