一个代表支持没有param和param的函数

时间:2018-01-28 10:26:46

标签: c#

我喜欢在一个地方集中代码并重用它而不是重复它。

我们有一个应该获得委托的方法的场景。 有时带参数,有时没有。

我只能触摸控制器而不是BL。 有没有办法避免重复GetLookupValues mehod? (在这种情况下,可选参数不起作用)。

public delegate List<TResult> LookupFunc<TResult>();
public delegate List<TResult> LookupFuncWithParam<TResult>(int id);
private ActionResult GetLookupValues<TResult>(LookupFuncWithParam<TResult> lookupFunc, int id)
{ 
  var listOfValues = lookupFunc(id);
  return ClientSideDTORender(listOfValues);
}

private ActionResult GetLookupValues<TResult>(LookupFunc<TResult> lookupFunc)
{
  var listOfValues = lookupFunc();
  return ClientSideDTORender(listOfValues);
}

public ActionResult GetAllCountries()
{
  return GetLookupValues<Country>(_blLookups.GetAllCountries);      
}



public ActionResult GetAllCities(int CountryId)
{
  return GetLookupValues<City>(_blLookups.GetAllCities, CountryId);
}

1 个答案:

答案 0 :(得分:2)

一种方法是使用lambdas:

private ActionResult GetLookupValues<TResult>(Func<TResult> lookupFunc)
{ 
  var listOfValues = lookupFunc();
  return ClientSideDTORender(listOfValues);
}

public ActionResult GetAllCountries()
{
  return GetLookupValues<Country>(_blLookups.GetAllCountries);      
}

public ActionResult GetAllCities(int CountryId)
{
  return GetLookupValues<City>(() => _blLookups.GetAllCities(CountryId));
}