2012-03-30 69 views
5

我有一个自定义的类,我用来建立表字符串。我想重写代码,以便我可以链接操作员。喜欢的东西:如何在C#中声明一个类,以便可以链接方法?

myObject 
    .addTableCellwithCheckbox("chkIsStudent", isUnchecked, isWithoutLabel) 
    .addTableCellwithTextbox("tbStudentName", isEditable) etc. 

所以好像我不得不每一种方法(函数)返回的对象本身,这样我就可以调用生成的对象上的其他方法(函数),但我不明白了解如何让ac#类引用自己。

任何帮助?

回答

6

所以,你会创建这样一个流畅的接口:

class FluentTable 
{ 
    //as a dumb example I'm using a list 
    //use whatever structure you need to store your items 
    List<string> myTables = new List<string>(); 

    public FluentTable addTableCellwithCheckbox(string chk, bool isUnchecked, 
                 bool isWithoutLabel) 
    { 
    this.myTables.Add(chk); 
    //store other properties somewhere 
    return this; 
    } 

    public FluentTable addTableCellwithTextbox(string name, bool isEditable) 
    { 
    this.myTables.Add(name); 
    //store other properties somewhere 
    return this; 
    } 
    public static FluentTable New() 
    { 
    return new FluentTable(); 
    } 
} 

现在你可以使用这样的:

FluentTable tbl = FluentTable 
        .New() 
        .addTableCellwithCheckbox("chkIsStudent", true, false) 
        .addTableCellwithTextbox("tbStudentName", false); 

这应该给你的,你需要如何去了解一个基本的想法它。请参阅fluent interfaces on wikipedia

做一个比较正确的做法是将实现一口流利的接口:

interface IFluentTable 
{ 
IFluentTable addTableCellwithCheckbox(string chk, bool isUnchecked, 
                 bool isWithoutLabel) 
IFluentTable addTableCellwithTextbox(string name, bool isEditable) 
//maybe you could add the static factory method New() here also 
} 

,然后实现它:class FluentTable : IFluentTable {}

+0

所有的答案都很好,但这个真的超越,谢谢这真的很有帮助 – 2012-04-01 20:24:01

7

使用this关键字作为返回值,这样你返回本身,你可以链永远:

ClassName foo() 
{ 
    return this; 
} 
+0

哎THX landr THX – 2016-11-19 04:39:27

0

确保每个方法返回一个声明要在你的链调用方法的接口。

EX公共IADD添加()

这样,如果IADD定义的add方法可以调用后添加添加添加后。你显然可以将otterh方法添加到同一个接口中。 这通常被称为流利的API

+0

通过这种方法,您可以使用几个类实现您的各种功能 – TGH 2012-03-30 04:57:49

3

这应该让你关闭。

public class SomeObject 
{ 
    public SomeObject AddTableCellWithCheckbox(string cellName, bool isChecked) 
    { 
     // Do your add. 

     return this; 
    } 
} 

祝你好运, 汤姆

7

这个符号被称为Fluent

对于你的榜样,最简单的形式是

public class MyObject { 
    public MyObject addTableCellwithCheckbox(...) { 
     ... 
     return this; 
    } 
    public MyObject addTableCellwithTextbox(...) { 
     ... 
     return this; 
    } 
} 

在更美丽的外形,你使用这些方法声明的接口(例如,IMyObject),并有myObject的类实现该接口。返回类型必须是接口,如上面的维基百科示例所示。

如果该类的源代码不可访问,那么也可以用类似的方法实现扩展类。

+2

+1 *流利*。 – 2012-03-30 05:02:54

相关问题