2016-05-04 26 views
4

我不知道我怎麼會寫這種類型的構造函數:構造沒有新的C#

Person p = Person.CreateWithName("pedro"); 
Person p1 = Person.CreateEmpty(); 

,並具有單獨的每個構造函數的代碼。

+1

這是一個靜態方法。 'public static Person CreateWithName(string name){return new Person(){...}; }' –

回答

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); 
    } 
    } 
6

這些都是所謂的工廠方法,技術上是類(person)上的靜態方法,然後在類(Person.Create)上調用。

從技術上講,他們在內部創建新的人 - 但它可以發生在私人建築師。

5

你剛纔創建的類中的靜態方法,即

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