基类和派生类中的静态字段
在abstract
基类中,如果我们有一些static
字段,那么它们会发生什么?
它们的范围是从该基类继承的类还是仅继承它的类型(每个子类都有自己的来自 abstract
基类的 static
字段副本)?
In an abstract
base class if we have some static
fields then what happens to them ?
Is their scope the classes which inherit from this base class or just the type from which it is inheriting (each subclass has it's own copy of the static
field from the abstract
base class)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
static
成员完全特定于声明类;子类不会获得单独的副本。这里唯一的例外是泛型;如果开放泛型类型声明静态字段,则该字段特定于构成封闭泛型类型的类型参数的精确组合;即Foo
将具有与Foo
不同的静态字段,假设这些字段是在Foo
上定义的。static
members are entirely specific to the declaring class; subclasses do not get separate copies. The only exception here is generics; if an open generic type declares static fields, the field is specific to that exact combination of type arguments that make up the closed generic type; i.e.Foo<int>
would have separate static fields toFoo<string>
, assuming the fields are defined onFoo<T>
.正如其他答案中所指出的,基类静态字段将在所有子类之间共享。如果您需要为每个最终子类提供单独的副本,则可以使用以子类名称作为键的静态字典:
As pointed out in other answer, the base class static field will be shared between all the subclasses. If you need a separate copy for each final subclass, you can use a static dictionary with a subclass name as a key:
以下代码说明静态成员的值在同一类型的抽象泛型的实例化之间共享。就像下面的示例一样,所有具有泛型类型“int”的实例化都将共享一个静态值,所有“string”都是另一个值。我最初认为它将在所有与泛型类型无关的实例化之间共享,但事实证明并非如此。
The following code illustrates that the static member's value is shared among the instantiation of the abstract generic of the same type. Like in the example below all instantiations with generic type 'int' would share one static value, all 'string's another value. I was initially thinking that it would be shared among all instantiation agnostic to the generic type, but turned out that's not the case.