c#中属性的单一模式>> [

问题描述 投票:1回答:7
我正在尝试为我的CsvConfiguration属性调整单例策略。

如果配置已经可用,只需返回配置。否则,获取配置并返回相同的代码,我就能构建此代码。

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属性调整单例策略。如果配置已经可用,则只需返回配置即可。否则,获取配置并返回相同的值,然后返回... ... >>

c# design-patterns .net-4.0 .net-4.5
7个回答
4
投票
认为您必须在getter中使用局部变量

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; } }


5
投票
您在get子句的顶部将单例设置为null:

3
投票
这是您的班级样子:

1
投票
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; } }

1
投票
如上所述,这不是一个单例模式。

如果您想坚持您所描述的想法,那么我会将您的代码更改为:


1
投票
此行: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) ....


0
投票
现在,我认为从C#6.0开始,您可以使用具有属性的初始值,例如:

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..? })();

© www.soinside.com 2019 - 2024. All rights reserved.