2016-11-14 32 views
-6

在C#中,字符串有這樣我怎麼能創造無限的財產

string a = ""; 
a.ToString().Length.ToString().ToUpper().ToLower().ToString().... 

無限的財產,我怎麼能創造這個

ClassName a = new ClassName(); 
a.text("message").title("hello").icon("user"); 

感謝狀,它的工作

 
    public class Modal 
    { 
     public Modal() 
     { 

     } 

     private string Date = null; 
     private string Text = null; 
     private string Title = null; 
     private string Icon = null; 
     private string Subtitle = null; 
     private string Confirm = "ok"; 
     private string Cancel = "cancel"; 
     private string Type = "warning"; 

     public Modal text(string text) { this.Text = text; return this; } 

     public Modal title(string title) { this.Title = title; return this; } 

     public Modal icon(string icon) { this.Icon = icon; return this; } 

     public Modal subtitle(string subtitle) 
     { 
      this.Subtitle = subtitle; 
      return this; 
     } 

     public Modal confirm(string confirm) { this.Confirm = confirm; return this; } 

     public Modal cancel(string cancel) { this.Cancel = cancel; return this; } 

     public Modal type(string type) { this.Type = type; return this; } 

     public void show(System.Web.UI.Page Page) 
     { 
      StringBuilder s = new StringBuilder(); 
      s.Append("{'date':'" + (DateTime.UtcNow.Ticks - 621355968000000000).ToString() + "','text':'" + Text + "','title':'" + Title + "','icon':'" + Icon + "','subtitle':'" + Subtitle + "','confirm':'" + Confirm + "','cancel':'" + Cancel + "','type':'" + Type + "'}"); 
      string _script = "showModal(" + s.ToString() + ");"; 
      ScriptManager.RegisterStartupScript(Page, Page.GetType(), (DateTime.UtcNow.Ticks - 621355968000000000).ToString(), _script, true); 
     } 

    } 
Modal m = new Modal(); 
m.text("this is text").title("this is title").icon("fa-car").type("danger").show(this); 

result

+8

它沒有「無限屬性」 - 它只是有各種返回''string'的方法。如果你讓你的方法返回相同的類型,你也可以這樣做... –

+2

你的例子甚至不會編譯,因爲Length是一個int而不是一個字符串。沒有屬性,只是鏈接的功能。 – TaW

+0

我不認爲你可以做'a.ToString()。Length.ToUpper()'因爲'Length'是一個'int' ..就像@JonSkeet所提到的那樣,只要每個方法都返回一個'string'就可以了繼續對結果調用'string'方法 – KMoussa

回答

1

string上的每種方法都只是返回一個string。 (好吧,差不多,你有一個.Length那裏是不正確的。)如果你從你的方法中返回你的對象,你可以實現相同的概念。 (在某些情況下,這可以被稱爲「一口流利的語法」,雖然string例子不一定真的。)

例如,假設您的.Title()方法是這樣的:

class ClassName 
{ 
    //... 

    public ClassName Title(string title) 
    { 
     this.Title = title; 
     return this; 
    } 
} 

然後調用任何時候someObj.Title("some string")該方法將返回對象本身:

var someObj = new ClassName(); 
someObj.Title("some title").SomeOtherOperation(); 

這不是「無限」,它只是返回上它調用的相同類型的方法。它可以返回本身或該類型的任何實例。當你這樣做時,一定要注意你正在構建的界面,因爲你可能會意外地創建相當不直觀的東西。 (對原始物體產生意想不到的副作用或對原始物體不產生預期效果的流暢鏈條)。

+0

謝謝你的回答,我會嘗試一下 –