鉴于以下代码:
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); }
}
你得到(有点预期的)输出“我们有 2 个小节,高兴!”。
这太棒了,我们现在有两倍的地方可以喝啤酒(显然),但我真正想要的是每个类(class)都有自己的缓存。我不想只在子类中实现这个缓存的原因是因为我的抽象类中还有一些方法需要能够对缓存进行操作(即迭代所有这些方法)。有没有办法做到这一点?我已经研究过为
foo
使用接口(interface),但该接口(interface)不允许将静态成员定义为接口(interface)的一部分。 最佳答案
foo 的每个派生类都应该定义获取缓存的方式/位置,因此每个派生类都可以(可能)拥有自己的缓存。 foo 中的方法可以在不知道实现的情况下引用 GetCache()。
public abstract class foo
{
public abstract ICache GetCache();
public void DoSomethingToCache()
{
ICache cache = this.GetCache();
cache.DoSomething();
}
}
public class bar : foo
{
public static ICache BarCache = new FooCache();
public override ICache GetCache()
{
return bar.BarCache;
}
}
public class FooCache : ICache { }