简体   繁体   中英

how would i call this function with a delegate as a parameter

I have repetitive code that i am trying to refactor into a generic function to generate a list of checkboxes from a list of objects (all lists of INamed).

The second parameter is a delegate that would call back into a function but i can't figure out how i would actually call this method. What is the best way to call a method with this delegate? (I am looking for an example of code that would call Checkboxlist function)

public delegate bool HasHandler(INamed named);

here is the generic method

static public string CheckboxList(IQueryable<INamed> allItems, HasHandler has, string name)
    {
        StringBuilder b = new StringBuilder();
        foreach (var item in allItems)
        {
            if (has(item))
            {
                b.Append("<input type='checkbox' class='checkboxes' name='" + name + "' value=" + item.Id + " checked />" + item.Name);
            }
            else
            {
                b.Append("<input type='checkbox' class='checkboxes' name='" + name + "' value=" + item.Id + " />" + item.Name);
            }
        }
        return b.ToString();
    }

You're doing it now:

if (has(item))  // This calls the delegate

That calls the delegate within the method. The syntax you have is correct, and should work.


As for calling CheckboxList - it sounds like you need to have the delegate defined. This can be any method which takes an "INamed" as a argument, and returns a boolean value. For example, if you had:

private bool myHandler(INamed named)
{
    return true;
}

You could call this with:

string result = CheckboxList(items, myHandler, "Foo");

Alternatively, you could pass a lambda here:

string result = CheckboxList(items, named => { return (named.Foo > 3); }, "Foo");

Very simple example:

public delegate bool HasHandler(INamed named);

// delete method matching HasHandler declaration
bool MyHandler(INamed named) {
    return true;
}

// method that passes your implemented delegate method as a parameter
void MyOtherMethod() {
    MyMethod(null, (n) => MyHandler(n)); // using lambda
    MyMethod(null, MyHandler); // not using lambda
}

// method that uses your implemented delegate method
// this would be like your CheckboxList method
void MyMethod(INamed o, HasHandler handler) {
    handler(o);
}

Notice the identifier handler is being used as a function with o (an object of INamed ) as a parameter.

EDIT

An example of calling your CheckboxList method:

CheckboxList(myItems, (n) => MyHandler(n), "myName");
CheckBoxList(yourItems, x => x.SomeProperty == "foo", "yourName");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM