1

所以我有一个函数,我将 Func 回调传回。我还想添加某种选择投影以便能够对对象进行投影,这意味着我只会执行一个数据库调用。该函数看起来像这样:

public T Get<T>(string id, Func<T> getItemCallback) where T : class
{
    item = getItemCallback();
    if (item != null)
    {
        doSomeThing(item);
        // Here I would like to call something else that is 
        // expecting a specific type.  Is there way to pass in a
        // dynamic selector?
        doSomethingElse(item.Select(x => new CustomType { id = x.id, name = x.name }).ToList());
    }
    return item;
}

void doSomethingElse(List<CustomType> custom)
{
    ....
}

Leme 显示我目前如何调用它,这可能会有所帮助:

public List<MyDataSet> GetData(string keywords, string id)
{
    return _myObject.Get(
       id, 
       () => db.GetDataSet(keywords, id).ToList());
    // Perhaps I could add another parameter here to 
    // handled the projection ????
}

多亏了 Reed,我才知道......看起来像这样:

public T Get<T>(string id, Func<T> getItemCallback, Func<T, List<CustomType>> selector) where T : class
{
     item = getItemCallback();
     if (item != null)
     {
          doSomething(item);
          var custom = selector(item);
          if (custom != null)
          {
              doSomethingElse(custom);
          }
     }
     return item;
 }

电话看起来像:

 public List<MyDataSet> GetData(string keywords, string id)
 {
     return _myObject.Get(
         id,
         () => db.GetDataSet(keywords, id).ToList(),
         x => x.Select(d => new CustomType { id = d.ReferenceId, name = d.Name })
               .ToList());
 }
4

1 回答 1

2

您还需要传入一个转换函数:

public T Get<T>(string id, Func<T> getItemCallback, Func<T, List<CustomType>> conversion) where T : class
{
    item = getItemCallback();
    if (item != null)
    {
        doSomeThing(item);

        if (conversion != null)
            doSomethingElse(conversion(item));
    }
    return item;
}
于 2013-09-17T16:31:57.730 回答