specify type of delegate parameter

345 views Asked by At

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;
            }
        }
    }
1

There are 1 answers

2
sstan On BEST ANSWER

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