2017-08-15 74 views
-10

我看到這個代碼在java中輸入。如何在C#中連續調用該方法?

PersonInfo result = personInfoBuilder 
      .setName("MISTAKE") 
      .setAge(20) 
      .setFavoriteAnimal("cat") 
      .setFavoriteColor("black") 
      .setName("JDM") 
      .setFavoriteNumber(7) 
      .build(); 

我試着用C#這種方式。

public class PersonInfo 
{ 
    public int Age { get; set; } 
    public string Name { get; set; } 
} 

public class PersonBuilder 
{ 
    private PersonInfo _personElement = null; 

    private int age; 
    private string name; 

    public void SetAge(int age) 
    { 
     this.age = age; 
    } 

    public void SetName(string name) 
    { 
     this.name = name; 
    } 

    public PersonInfo GetPerson() 
    { 
     _personElement = _personElement ?? new PersonInfo(); 
     _personElement.Age = age; 
     _personElement.Name = name; 

     return _personElement; 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     PersonBuilder builder = new PersonBuilder(); 
     builder.SetName("he") 
       .SetAge(20); 

    } 
} 

我有一個錯誤[資源不可用於匿名訪問。需要客戶端身份驗證。],

如何在C#中像Java一樣連續調用方法?

+0

你是怎麼試的? –

+4

*「我看到了一輛摩托車越野車,我用我的車試了一下,但沒有奏效」* – Filburt

+2

創建一個PersonInfoBuilder類,初始化一個實例,讓每個方法返回這個實例,然後你可以鏈接它。 'Build'方法返回具有指定屬性的PersonInfo的實例。 –

回答

3

您建議的代碼稱爲生成器模式。這裏是我如何在我的C#代碼中執行構建器模式。

生成器類

class PersonInfo 
    { 
     private string name, animan, color; 
     private int age, num; 

     private PersonInfo() { } 

     public class Builder 
     { 
      PersonInfo info = new PersonInfo(); 

      public Builder setName(string name) { info.name = name; return this; } 
      public Builder setAge(int age) { info.age = age; return this; } 
      public Builder setFavoriteAnimal(string animan) { info.animan = animan; return this; } 
      public Builder setFavoriteColor(string color) { info.color = color; return this; } 
      public Builder setFavoriteNumber(int num) { info.num = num; return this; } 

      public PersonInfo build() 
      { 
       return info; 
      } 
     } 
    } 

,這裏是你如何使用它。

PersonInfo.Builder personInfoBuilder = new PersonInfo.Builder(); 
PersonInfo result = personInfoBuilder 
            .setName("MISTAKE") 
            .setAge(20) 
            .setFavoriteAnimal("cat") 
            .setFavoriteColor("black") 
            .setName("JDM") 
            .setFavoriteNumber(7) 
            .build();