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)
有更好的模式吗?
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)
这种方法不那么优雅,但更简单一点.
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)
这会隐藏内部数据,并且只能为您提供静态列表的一个实例,而每个通用参数组合只有一个实例.