0

im trying to use TryGetValue.

to Invoke a delegate inside Method i use dictionary to select one delegate and then Invoke it.

the dictionary type is

Dictionary<string, Action<Mesh>> _meshActions;

and the action type is

Action<Mesh>

So here it seems i can not declare action in delegate parameter correctly.

        Method(null, "mesh", ( action => //How to specify type of action
        {
            _meshActions.TryGetValue(_reader.LocalName, out action);

            try { action(mesh); }
            catch 
            {
                //do nothing 
            }
        }));

Compiler expects out be type of Action<Mesh> but how can i set the action type?

before using TryGetValue i used dictionary normally

but because sometimes i got error for Key not found so i decided to use TryGetValue

this is the code without TryGetValue and works fine if all Keys find.

Method(null, "mesh", () => _meshActions[_reader.LocalName](mesh));

Edit: note that action is nothing outside delegate. i just want to send parameter inside TryGetValue and use its resault.

and here is the Method

    private static void Method(string enterElement, string exitElement, Action loadElement)
    {
        while (_reader.Read())
        {
            if (StateElement(State.Enter, enterElement))
            {
                loadElement.Invoke();
            }
            else if (StateElement(State.Exit, exitElement))
            {
                return;
            }
        }
    }
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118

1 Answers1

2

action needs to be declared locally in the delegate, not as a parameter.

    Method(null, "mesh", ( () => //How to specify type of action
    {
        Action<Mesh> action;
        _meshActions.TryGetValue(_reader.LocalName, out action);

        try { action(mesh); }
        catch 
        {
            //do nothing 
        }
    }));
sstan
  • 35,425
  • 6
  • 48
  • 66
  • No, it's not dynamic. The signature of your `Method` method specifies that it expects an `Action`, plain and simple. That means that it expects a delegate with this signature: `() => { ... }`. No parameters and no return value. Where is the confusion? EDIT: I must have dreamed there was a comment there :) – sstan Jun 10 '15 at 20:43
  • oh thanks i got it. i dont know why i forget simple things when i get in deep coding. delegates are forgetful for me.thanks for the answer!Edit : haha i asked and i guess it was stupid question because of late answer and ...umm sorry for that! – M.kazem Akhgary Jun 10 '15 at 20:45