2016-11-14 3 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

「無限の特性」はありません。単に「文字列」を返すさまざまな方法があります。あなたのメソッドが同じ型を返すようにしても、それを行うことができます。 –

+2

長さが文字列ではないので、あなたの例はコンパイルされません。プロパティはなく、ちょうど連鎖した関数です。 – TaW

+0

@TheString()。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

ありがとうございました試してみる –

関連する問題