从默认构造函数中添加静态类中的实例类时出现Stack-Overflow异常

问题描述 投票:-1回答:2
public class Form
{
    internal static Dictionary<string, Form> Cache = new 
     Dictionary<string, Form>();
    public string FormID{get;set;} = string.Empty;

    public Form()
    {
        if (!Cache.ContainsKey(FormID))
            Cache.Add(FormID, new Form());

       // exception here because new Form() is always called again
    }
}

我想在Cache中创建类Form的对象实例。如果Cache包含FormID属性,则静态字典Cache不会发生任何事情。

缓存必须为具有唯一FormID的Form中的每个实例保存单个实例。这意味着每个Form实例都在具有相同FormID的Cache中具有实例。因此,通过克隆缓存创建新实例将很快。这就是我需要做的。

Camilo Terevinto在下面回答得很好。

c# .net stack-overflow default-constructor
2个回答
1
投票

这段代码没有意义:

if (!Cache.ContainsKey(FormID))
    Cache.Add(FormID, new Form());

您将始终检查/添加FormId的默认值。有了这个,你在该词典中只会有一个键/值对,所以使用词典会很浪费。

您应该为此使用工厂方法,并保留默认构造函数:

private Form()
{
}

public static Form BuildForm(string formId)
{
    if (!Cache.ContainsKey(formId))
    {
        Cache.Add(formId, new Form());
    }

    return Cache[formId].DeepClone();  // using DeepCloner extension
}

0
投票

你可能想在this中添加Cache

public class Form
{
    internal static Dictionary<string, Form> Cache = new
        Dictionary<string, Form>();

    public string FormID { get; private set; }

    public Form(string formID)
    {
        this.FormID = formID;
        if (!Cache.ContainsKey(formID))
            Cache.Add(formID, this); // <--- this instead of new Form();
    }
}

this指的是当前构建的Form实例。

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