Reputation: 169
[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();
}
}
);
}
Upvotes: 0
Views: 330
Reputation: 125630
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))
}
Upvotes: 3