문제

[Actually, I am not sure the problem is relate to anonymous and delgate or not.]

In my application, I use the asynchronous for create new item. In AddNew method, it will call create a new item from the repo class then add it to list item. The create method has parameter but it has a return value.

The problem is I really don't know how to call a create method with the anonymous.

The code as following.

    protected void AddNew()
    {
        _repo.Create(() => AddToListItem(x)) // I want the value (x) that return from repository.Create to use with AddToListItem(x)
    }

    public P Create(Action completed = null)
    {
        var p = new P();
        Insert(p);
        return p;
    }

    public void Insert(P p, Action completed = null)
    {
        _service.Insert(p,
            () =>
            {
                if (onCompleted != null)
                {
                    onCompleted();
                }
            }
            );
    }
도움이 되었습니까?

해결책

Instead of parameterless Action use generic Action<T>:

Encapsulates a method that has a single parameter and does not return a value.

Your code should looks like that:

public P Create(Action<P> completed = null)
{
    var p = new P();
    Insert(p, completed);
    return p;
}

public void Insert(P p, Action<P> completed = null)
{
    _service.Insert(p,
        () =>
        {
            if (completed != null)
            {
                completed(p);
            }
        }
        );
}

You have to also change your lambda expression to match Action<P>:

protected void AddNew()
{
    _repo.Create((x) => AddToListItem(x))
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top