简体   繁体   中英

Static field that isn't shared

I have the following class:

public abstract class Manager<T> {

    protected static List<T> items = new List<T>();

    public static void Register(T item){
        if(!items.Contains(item)){
            items.Add(item);
        }
    }

    public static void DeRegister(T item){
        if(items.Contains(item)){
            items.Remove(item);
        }
    }

}

I then have classes that extend the above class:

public class InventoryManager : Manager<InventoryItem> {

}

Or:

public class ExampleManager : Manager<ExampleItem> {

}

The thing that will be an issue, is that items is static, so the two classes that extend manager will be sharing the same field. What can I do to make it so that they don't share the field yet I can still call InventoryManager.Regiser(this) ?

As requested in the comments, rephrased as an answer:

Manager<InventoryItem> and Manager<ExampleItem> are already distinct types with distinct static fields. Your code should do exactly what you want it to. You don't have any Manager class, you only have a Manager<T> generic class where each generic type argument gives you a different concrete class. A different concrete class means different static fields. You should be able to see this easily by just trying it. Add an item to InventoryManager.items , then inspect ExampleManager.items.Count .

It was also pointed out in the comments that Manager<InventoryItem>.items and Manager<ExampleItem>.items cannot be the same object, since they have different types. That's correct. However, it's worth keeping in mind that you get different static fields even for non-dependent field types.

using System;

class GenericBaseClass<T>
{
    public static int field;
}

class DerivedClass1 : GenericBaseClass<DerivedClass1>
{
}

class DerivedClass2 : GenericBaseClass<DerivedClass2>
{
}

static class Program
{
    static void Main()
    {
        DerivedClass1.field = 2;
        DerivedClass2.field = 3;
        Console.WriteLine($"DerivedClass1.field: {DerivedClass1.field}");
        Console.WriteLine($"DerivedClass2.field: {DerivedClass2.field}");
    }
}

Output:

DerivedClass1.field: 2
DerivedClass2.field: 3

Static fields or properties not related to instance object. They are related to type object.

https://msdn.microsoft.com/en-us/library/98f28cdx.aspx

You should declare Register and DeRegister methods as non static.

In addition

protected static List<T> items = new List<T>();

will not be the same field for both types as depending on T it will be different types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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