c# - Singleton:第一次如何实例化Singleton?

标签 c# singleton

我有这个单例类:

public class Utente
{
    private static readonly Lazy<Utente> lazy =
    new Lazy<Utente>(() => new Utente());

    public static Utente Instance
    {
        get
        {
            return lazy.Value;
        }
        set
        {

        }
    }

    public string name { get; set; }
    public string lastname { get; set; }
    public int id { get; set; }
    public int issuperuser { get; set; }
    public string persontype { get; set; }
    public int idpersontype { get; set; }
    public string token { get; set; }
    public string[] permissions { get; set; }
    public List<Mese> mese { get; set; }
}

我第一次需要实例惰性。我怎么做?我需要第一次实例化该类,以便将其保存在程序的整个其余部分中。

现在我需要在这个类中使用它:

Utente u = new Utente();
WebRequest richiesta = (HttpWebRequest)WebRequest.Create(URL);
WebResponse risposta = (HttpWebResponse)CreateLoginRequest(richiesta).GetResponse();
StreamReader dati = new StreamReader(risposta.GetResponseStream());
string output = dati.ReadToEnd();
u = JsonConvert.DeserializeObject<Utente>(output);
risposta.Close();

Utente() 正确还是我应该使用其他代码? 编辑:

Utente u = new Utente();
WebRequest richiesta = (HttpWebRequest)WebRequest.Create(URL);
WebResponse risposta = (HttpWebResponse)CreateLoginRequest(richiesta).GetResponse();
StreamReader dati = new StreamReader(risposta.GetResponseStream());
string output = dati.ReadToEnd();
u = JsonConvert.DeserializeObject<Utente>(output);
risposta.Close();

Utente 类只需实例化一次,以便我可以在所有程序中使用该值。那么为什么我在另一个类(class)中这样做:`

if (verifica && (Utente.Instance.persontype == "Datore")) 

Utente.Instance.persontype 结果为空?

最佳答案

第一个问题:您尚未通过公共(public)构造函数禁用 Utente 类实例创建。代码的第一行创建一个新实例:

Utente u = new Utente();

正如其他人已经提到的,您必须禁止在此类之外创建单例类的新实例。将构造函数设为私有(private):

private Utente() { }

现在是第二个问题 - 您想要使用 Newtonsoft JSON 反序列化器填充单例的属性。 即使构造函数是私有(private)的,每次反序列化某些字符串时,反序列化器都会创建 Utrente 类的新实例:

var newInstance = JsonConvert.DeserializeObject<Utente>(output); // 'output' is json string

所以你不应该使用DeserializeObject方法。您应该使用 PopulateObject方法并传递已存在的单例实例以由 Newtonsoft JSON 填充:

JsonConvert.PopulateObject(output, Utente.Instance); 

还有一个小注意事项 - 单例的 Instance 属性不需要 set 方法。使用 C# 6 Expression-Bodied 成员,您可以将此属性简化为:

public static Utente Instance => lazy.Value;

关于c# - Singleton:第一次如何实例化Singleton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44497878/

相关文章:

.net - Context.Current 模式的缺点?

c++ - obj1是如何被引用的,如果为NULL则调用show方法

c# - 如何将 int 转换为枚举值?

c# - 使用非托管资源

c# - 定时器触发更新面板更新导致失去焦点

c# - 对 Lazy<T> 单例代码的修改

C# - 两种形式的相同控制?

c# - 使用 Microsoft.Data.SqlClient 2.0 时无法从单元测试加载 DLL 'Microsoft.Data.SqlClient.SNI.x86.dll'

c# - 为什么在ApiController中获取ActionName这么复杂?更简单的方法?

ios - 完成处理程序如何返回错误的 ViewController?