我有这段代码,无法弄清楚如何通过Lambda表达式进行简化?

public void LoadEntities(QueryBuilder<Device> query, Action<ServiceLoadResult<Device>> callback, object state)
{
    InvokeOperation<List<DivisionHierarchy>> obj = this.Context.GetAllDivisions();

    obj.Completed += new EventHandler(obj_Completed);
}

void obj_Completed(object sender, EventArgs e)
{
    try
    {
        if (sender is InvokeOperation<List<DivisionHierarchy>>)
        {
            ObservableCollection<DivisionHierarchy> divisions =
                new ObservableCollection<DivisionHierarchy>((sender as InvokeOperation<List<DivisionHierarchy>>).Value);
        }
    }
    catch
    {
    }
}

最佳答案

您的问题有点太笼统了,所以我在这里猜测,但是这里的lambda表达式唯一的地方是挂接到事件上。因此,您可以执行以下操作,而不用使用单独的obj_Completed方法:

    public void LoadEntities(QueryBuilder<Device> query, Action<ServiceLoadResult<Device>> callback, object state)
    {
        InvokeOperation<List<DivisionHierarchy>> obj = this.Context.GetAllDivisions();

        obj.Completed += (sender, e) =>
        {
           try
           {
               if (sender is InvokeOperation<List<DivisionHierarchy>>)
               {
                   ObservableCollection<DivisionHierarchy> divisions =
                       new ObservableCollection<DivisionHierarchy>((sender as InvokeOperation<List<DivisionHierarchy>>).Value);

               }
           }
           catch
           {
           }
       }
     }

关于c# - Lambda表达式和InvokeOperation,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9978564/

10-12 02:13