在泛型类中需要一个非常静态的字段,或者如何保护其可见性?

naw*_*fal 3 c# generics singleton static

我希望有一个类:

public class Forest<S, T>
{
    static IList<Animal> coolGuys = new List<Animal>();
}
Run Code Online (Sandbox Code Playgroud)

但我想要coolGuys非常静态,这意味着它必须在应用程序的整个生命周期中都是唯一的.而现在它不是.ReSharper警告说,MS不鼓励这种模式,但是如何实现我想要的呢?

可能我需要通过创建另一个静态类来完成更多工作,并在那里有一个公共静态字段另一个单例类中的公共实例字段.可以有一个冗余的公共类来保存一个静态字段,但我要避免的是该字段是公共/内部的.我的意思coolGuys是,只是意味着Forest<,>,为什么要将不连贯的事物暴露给外界.

public class Forest
{
    public static IList<Animal> coolGuys = new List<Animal>(); //want to avoid
}

public class Forest<S, T>
{
    Forest.coolGuys.Add(cutie);
}
Run Code Online (Sandbox Code Playgroud)

有更好的模式吗?

Tim*_*ora 8

方法1 - 注入州提供者

  1. 创建一个存储数据的类型.
  2. 使用接口抽象它,因此您可以根据需要注入不同的提供程序(例如,用于测试).
  3. 消费类不关心实现,除了它保证有状态.
  4. 并发字典负责线程安全.
public interface IStateProvider
{
    void Store( string key, object value );
    object Get( string key );
}

public class StateProvider : IStateProvider
{
    private static ConcurrentDictionary<string, object> _storage = new ConcurrentDictionary<string, object>();

    public void Store( string key, object value )
    {
        // add to storage
    }

    public object Get( string key )
    {
        // get from storage
    }
}

public class Forest<T1, T2>
{
    private IStateProvider _stateProvider;

    public Forest( IStateProvider stateProvider )
    {
        _stateProvider = stateProvider;
    }

    public void Foo()
    {
        // do something with the stateful value
    }
}

// of course, you could do this with a DI framework
var stateProvider = new StateProvider();
var forest = new Forest<Foo, Bar>( stateProvider );
Run Code Online (Sandbox Code Playgroud)

方法2 - 基类

这种方法不那么优雅,但更简单一点.

public abstract class ForestBase
{
    private static List<object> _staticList = new List<object>();

    protected List<object> StaticList
    {
        get { return _staticList; }
    }
}

public class Forest<T1, T2> : ForestBase
{
    public void Foo()
    {
        StaticList.Add( 12345 );
    }
}
Run Code Online (Sandbox Code Playgroud)

这会隐藏内部数据,并且只能为您提供静态列表的一个实例,而每个通用参数组合只有一个实例.

  • 一个小小的音符 - 可能你的意思是`base.StaticList`而不是`this.StaticList`.`this`让代码有点谎言) (3认同)