How to declare a class in C # so that I can hook on methods?

I have a custom class that I use to create table rows. I would like to rewrite the code so that I can bind the operators. Sort of:

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

So, it looks like each of these methods (functions) returns the object itself, so that I can then call another method (function) in the resulting object, but I cannot figure out how to get the aC # class to refer to itself.

Any help?

+5
source share
5 answers

So, you would create a free interface like this:

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();
  }
}

Now you can use it as follows:

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

This should give you a general idea of โ€‹โ€‹how you need to do this. See the free interface 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 {}

+6

this , , , :

ClassName foo()
{
    return this;
}
+7

Fluent.

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

(, IMyObject) , MyObject . , .

, .

+7

.

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

        return this;
    }
}

,

+3

, , , .

EX public IAdd Add()

That way, if IAdd has defined an add method, you can call Add after Add after Add. You can obviously add otterh methods to the same interface. This is commonly called the free API.

0
source

All Articles