不使用new关键字的构造函数C#

4
我想知道如何编写这种类型的构造函数:
Person p = Person.CreateWithName("pedro");
Person p1 = Person.CreateEmpty();

每个构造函数的代码都应该分开存放。

1
这是一个静态方法。public static Person CreateWithName(string name) { return new Person() {...}; } - p.s.w.g
3个回答

6

这些被称为工厂方法,实际上是在类(Person)上的静态方法,然后在类上进行调用(Person.Create)。

从技术上讲,它们使用私有构造函数内部创建了 Person 对象,


5

您只需在该类中创建一个静态方法,例如:

class Person {
  public Person(string name) {
    //Constructor logic
  }
  public static Person CreatePerson() {
    return new Person(string.Empty);
  }
}

2
你可以这样实现它:
  public class Person {
    // Private (or protected) Constructor to ensure using factory methods
    private Person(String name) { 
      if (null == name)
        name = "SomeDefaultValue";

      //TODO: put relevant code here
    }

    // Factory method, please notice "static"
    public static Person CreateWithName(String name) {
      return new Person(name); 
    }

    // Factory method, please notice "static"
    public static Person CreateEmpty() {
      return new Person(null); 
    } 
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接