Given the following code:
using System.Collections.Generic; static class Program { static void Main() { bar Bar = new bar(); baz Baz = new baz(); System.Console.WriteLine( "We have {0} bars, rejoice!", bar.Cache.Count); } } public abstract class foo { public static List<foo> Cache = new List<foo>(); } public class bar : foo { public bar() { Cache.Add(this); } } public class baz : foo { public baz() { Cache.Add(this); } }
You get the (somewhat expected) conclusion "We have 2 bars, rejoice!".
It's awesome, now we have twice as many places for beer (apparently), but I really want each class to have its own cache. The reason I don't want to just implement this cache in a subclass is because I also have some methods in my abstract class that should be able to work in the cache (namely, iterating over all of them). Is there any way to do this? I have considered using the interface for foo , but the interface does not allow static members to be defined as part of the interface.
source share