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

Stack-Overflow exception when adding instance class inside static class from default constructor

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

我想在缓存中创建 class 表单对象的实例。如果 Cache 包含 FormID 属性 那么静态字典 Cache 什么也不会发生。

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

Camilo Terevinto 在下面回答得很好。

这段代码没有意义:

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

您将永远是 checking/adding 默认值 FormId。这样一来,您在该词典中将永远只有一个 key/value 对,因此使用词典将是一种浪费。

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

private Form()
{
}

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

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

您可能需要在 Cache 中添加 this:

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实例