如果配置已经可用,只需返回配置。否则,获取配置并返回相同的代码,我就能构建此代码。
public Rootpdf pdfConfiguration
{
get
{
Rootpdf pdfConfiguration = null;
try
{
if (pdfConfiguration == null)
{
//retrieve the configuration file.
//load the configuration and return it!
}
else
{
return pdfConfiguration;
}
}
catch (Exception e)
{
Log.Error("An error occurred while reading the configuration file.", e);
}
return pdfConfiguration;
}
}
优点(我希望):每当需要我的pdfConfiguration时,如果已经可用,我都可以退还。无需每次加载配置文件并计算配置。
我的查询:该死了! Resharper告诉代码
if (pdfConfiguration == null) //The expression is always true.
Reshaper确实存在问题,因为它不明白我是否遵循此单例模式?
或
我完全不遵循单例模式吗?
我正在尝试为我的CsvConfiguration属性调整单例策略。如果配置已经可用,则只需返回配置即可。否则,获取配置并返回相同的值,然后返回... ... >>
private static Rootpdf _pdfConfiguration ;
public static Rootpdf pdfConfiguration
{
get
{
try
{
if (_pdfConfiguration == null)
{
//retrieve the configuration file.
//load the configuration and return it!
}
else
{
return _pdfConfiguration;
}
}
catch (Exception e)
{
Log.Error("An error occurred while reading the configuration file.", e);
}
return _pdfConfiguration;
}
}
class MySingletonClass
{
private static UserSettings instance = null;
/// <summary>
/// Default protected constructor.
/// </summary>
protected MySingletonClass()
{
}
/// <summary>
/// Invoke the singleton instance.
/// </summary>
public static MySingletonClass Instance()
{
if (instance == null)
instance = new MySingletonClass();
return instance;
}
}
如果您想坚持您所描述的想法,那么我会将您的代码更改为:
if (pdfConfiguration == null)
由于此行(正好在Rootpdf pdfConfiguration = null;
之前)将始终为true。您需要做的是将最后一行(Rootpdf pdfConfiguration = null;
)放在Get
方法之外。每次都会停止将变量初始化为null。 private static Rootpdf pdfConfiguration = null;
public Rootpdf PdfConfiguration
{
get
{
try
{
if (pdfConfiguration == null)
....
static public Rootpdf pdfConfiguration { get; } = new Func<Rootpdf>(() => {
//retrieve the configuration file.
//load the configuration and return it!
return new Rootpdf(); // Something like this perhaps..?
})();