简体   繁体   English

基础 class 和派生类中的 Static 字段

[英]Static fields in a base class and derived classes

In an abstract base class if we have some static fields then what happens to them?abstract基础 class 中,如果我们有一些static字段,那么它们会发生什么?

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)?他们的 scope 是从这个基础 class 继承的类,还是只是它所继承的类型(每个子类都有它自己的static abstract基类字段的副本)?

static members are entirely specific to the declaring class; static成员完全特定于声明class; subclasses do not get separate copies.子类没有单独的副本。 The only exception here is generics;这里唯一的例外是 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;如果开放泛型类型声明了 static 字段,则该字段特定于构成封闭泛型类型的 arguments 类型的确切组合 ie Foo<int> would have separate static fields to Foo<string> , assuming the fields are defined on Foo<T> .Foo<int>将有单独的 static 字段到Foo<string> ,假设这些字段是在Foo<T>上定义的。

As pointed out in other answer, the base class static field will be shared between all the subclasses.正如在其他答案中指出的那样,基础 class static 字段将在所有子类之间共享。 If you need a separate copy for each final subclass, you can use a static dictionary with a subclass name as a key:如果您需要每个最终子类的单独副本,您可以使用 static 字典,其中子类名称作为键:

class Base
{
    private static Dictionary<string, int> myStaticFieldDict = new Dictionary<string, int>();

    public int MyStaticField
    {
        get
        {
            return myStaticFieldDict.ContainsKey(this.GetType().Name)
                   ? myStaticFieldDict[this.GetType().Name]
                   : default(int);
        }

        set
        {
            myStaticFieldDict[this.GetType().Name] = value;
        }
    }

    void MyMethod()
    {
        MyStaticField = 42;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM