2010-01-13 63 views
4

在C#中如何實現一個有能力鏈方法於一體的自定義類,因此一個能寫這樣的事:如何實現方法鏈接?

myclass.DoSomething().DosomethingElse(x); 

等等

謝謝!

+0

查看http://stackoverflow.com/questions/1119799/method-chaining-in-c – 2010-01-13 09:47:20

回答

10

鏈接是一個很好的解決方案,從現有的情況下產生新的實例:

public class MyInt 
{ 
    private readonly int value; 

    public MyInt(int value) { 
     this.value = value; 
    } 
    public MyInt Add(int x) { 
     return new MyInt(this.value + x); 
    } 
    public MyInt Subtract(int x) { 
     return new MyInt(this.value - x); 
    } 
} 

用法:

MyInt x = new MyInt(10).Add(5).Subtract(7); 

你也可以使用這種模式修改現有的實例,但一般不建議:

public class MyInt 
{ 
    private int value; 

    public MyInt(int value) { 
     this.value = value; 
    } 
    public MyInt Add(int x) { 
     this.value += x; 
     return this; 
    } 
    public MyInt Subtract(int x) { 
     this.value -= x; 
     return this; 
    } 
} 

用法:

MyInt x = new MyInt(10).Add(5).Subtract(7); 
+0

+1舉一個很好的例子。通常這個概念被稱爲Fluent接口 - 參見http://en.wikipedia.org/wiki/Fluent_interface。雖然在技術上你不使用一個,但是引入一個將是微不足道的。 – 2010-01-13 10:02:07

1

DoSomething應該用DoSomethingElse方法返回一個類實例。

1

對於可變類,像

class MyClass 
{ 
    public MyClass DoSomething() 
    { 
     .... 
     return this; 
    } 
} 
0

你的方法應該返回this還是取決於你想要什麼的引用到另一個(可能是新的)對象acheive