简体   繁体   中英

Manipulate object's fields by a delegate passed as parameter

I'm crating a custom dialog class. It takes a list of OptionObject objects, in constructor. At some point it's displayed and depending on which option the user clicks performs an action that is injected into OptionObject.

public class OptionObject
    {
        public object Id { get; set; }
        public string Text { get; set; }

        public Action Action { get; set; }

        public OptionObject(object id, string text, Action action)
        {
            this.Id = id;
            this.Text = text;
            this.Action = action;
        } 
}

This is how the actions are invoked by DialogWindow:

this.Options.Tap += (sender, args) =>   // Options is a ListBox
                                    {
                                        var o = sender as ListBox;
                                        var x = o.SelectedItem as OptionObject;
                                        if(x!=null)
                                            x.Action();
                                        this.IsOpen = false;
                                    };

And finally I'm trying to use my dialog on another page:

foreach (var o in eventsOnDate)
                {
                    chooseEventDialogWindow.Data.OptionsList.Add(new OptionObject(o.Text, ()=> /*### don't know what to put in here ###*/ ));
                }

The problem is that OptionObject.Action sometimes needs OptionObject.Id property. How can I access it in the sniped right above?

EDIT

I wouldn't like to pass any parameters into this lambda expression if it's possible, as sometime there's no need for this Id. Optional parameters would be fine if this is the right way to go.

PS

This is not important for the question but to avoid unnecessary discussion this dialog is based on telerik's RadWindow.

An Action is a method that has no parameters and does not return a value, so you either have to enclose your OptionObject.ID property when you create the Action delegate:

object id = new object();
Action act = () => DoSomethingWithIdAndReturnVoid(id);
OptionObject opt = new OptionObject(id, "some text", act);
opt.Action();

Or do like Henk suggests in his comment, ie, create an Action that has an input parameter :

object id = new object();
Action<object> act = (x) => DoSomethingWithIdAndReturnVoid(x);
OptionObject opt = new OptionObject(id, "some text", act);
opt.Action(opt.ID);

Just be aware that changes to enclosed variables only work properly when dealing with Reference Types .

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