我正在使用
.NET 4's Lazy<T> type
方法创建一个单例实例。但我想将配置文件的三个文件路径传递给返回单例的属性Instance
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
如果你真的想使用单例,也许可以考虑添加一些 init/config 方法。您的单例必须在访问实例之前进行初始化(如果不是,则抛出异常)。我不喜欢这个解决方案,因为 Singleton 类的用户需要以某种方式了解 init 步骤。
/// <summary>
/// Singleton class
/// </summary>
public sealed class Singleton
{
private static Lazy<Singleton> lazy = null;
/// <summary>
/// You can use this param to pass to your base class
/// </summary>
/// <param name="parameter"></param>
private Singleton(int parameter)
{
}
/// <summary>
/// Creating single object
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public static Singleton CreateSingletonObj(int parameter)
{
if (lazy == null)
{
lazy = new Lazy<Singleton>(() => new Singleton(parameter));
}
return lazy.Value;
}
}