Factory vs instance constructors

后端 未结 10 1892
渐次进展
渐次进展 2020-12-13 17:41

I can\'t think of any reasons why one is better than the other. Compare these two implementations:

public class MyClass
{
    public MyClass(string fileName         


        
10条回答
  •  死守一世寂寞
    2020-12-13 18:15

    Methods that do the construction for you are super useful for:

    public class Class
        {
            public static List FromFiles(IEnumerable paths)
            {
                List instances = new List();
                foreach (string path in paths)
                {
                    instances.Add(new Class() { Path = path });
                }
                return instances;
            }
    
            public string Path { get; set; }
        }
    

    ...since "normal" constructors cannot do this.

提交回复
热议问题