具有返回值的匿名委托

时间:2014-01-02 06:52:34

标签: c# asynchronous callback delegates anonymous

[实际上,我不确定问题是否与匿名和delgate有关。]

在我的应用程序中,我使用异步来创建新项目。在AddNew方法中,它将调用从repo类创建一个新项,然后将其添加到列表项。 create方法有参数但它有一个返回值。

问题是我真的不知道如何使用匿名调用create方法。

代码如下。

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

1 个答案:

答案 0 :(得分:3)

而不是无参数Action使用通用Action<T>

  

封装具有单个参数且不返回值的方法。

您的代码应如下所示:

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

您还必须更改lambda表达式以匹配Action<P>

protected void AddNew()
{
    _repo.Create((x) => AddToListItem(x))
}