如何强制C#构造函数成为工厂?

Edw*_*uay 0 c# constructor instantiation

下面的代码包含两个类:

  • SmartForm(简单模型类)
  • SmartForms(包含一组SmartForm对象的复数类)

我希望能够像这样实例化单数和复数类(即我不想要工厂方法GetSmartForm()):

SmartForms smartForms = new SmartForms("all");
SmartForm smartForm = new SmartForm("id = 34");
Run Code Online (Sandbox Code Playgroud)

要合并逻辑,只有复数类才能访问数据库.当被要求实例化时,单数类将简单地实例化一个复数类,然后从复数对象的集合中选择一个对象并成为该对象.

我怎么做?我试图分配this不起作用的对象.

using System.Collections.Generic;

namespace TestFactory234
{
    public class Program
    {
        static void Main(string[] args)
        {
            SmartForms smartForms = new SmartForms("all");
            SmartForm smartForm = new SmartForm("id = 34");
        }
    }

    public class SmartForm
    {
        private string _loadCode;

        public string IdCode { get; set; }
        public string Title { get; set; }

        public SmartForm() {}

        public SmartForm(string loadCode)
        {
            _loadCode = loadCode;
            SmartForms smartForms = new SmartForms(_loadCode);
            //this = smartForms.Collection[0]; //PSEUDO-CODE
        }

    }

    public class SmartForms
    {
        private string _loadCode;

        public List<SmartForm> _collection = new List<SmartForm>();
        public List<SmartForm> Collection
        {
            get
            {
                return _collection;
            }
        }

        public SmartForms(string loadCode)
        {
            _loadCode = loadCode;
            Load();
        }

        //fills internal collection from data source, based on "load code"
        private void Load()
        {
            switch (_loadCode)
            {
                case "all":
                    SmartForm smartFormA = new SmartForm { IdCode = "customerMain", Title = "Customer Main" };
                    SmartForm smartFormB = new SmartForm { IdCode = "customerMain2", Title = "Customer Main2" };
                    SmartForm smartFormC = new SmartForm { IdCode = "customerMain3", Title = "Customer Main3" };
                    _collection.Add(smartFormA);
                    _collection.Add(smartFormB);
                    _collection.Add(smartFormC);
                    break;
                case "id = 34":
                    SmartForm smartForm2 = new SmartForm { IdCode = "customerMain2", Title = "Customer Main2" };
                    _collection.Add(smartForm2);
                    break;
                default:
                    break;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

你不能让一个对象"成为"另一个.

使用静态方法而不是构造函数(并使构造函数为private/internal/whatever,以便只有静态方法才能访问它们).使用静态方法比构造函数有很多好处:

  • 如果合适,您可以返回null
  • 如果合适,您可以返回现有对象
  • 你可以做很多工作然后调用一个只设置字段的简单构造函数

缺点是它们不能与C#集合/对象初始化器一起使用:(

静态方法的替代方法(无可否认,依赖注入效果不佳)就是在其上有一个单独的工厂和调用实例方法.