我有一个字典设置如下:
private Dictionary<string, Promotion> availablePromotions = new Dictionary<string, Promotion>()
{
{ "BestHorseRacingFreeBetSidebarOffers", Client.GetHorseRacingSignUpOffersSidebarWidget() },
{ "BestHorseRacingBettingSidebarOffers", Client.GetHorseRacingBettingOffersSidebarWidget() },
{ "BestHorseRacingBettingOffers", Client.GetBestHorseRacingBettingOffersWidget() },
{ "BestHorseRacingFreeBetOffers", Client.GetBestHorseRacingSignUpOffersWidget() },
{ "BestFootballBettingOffers", Client.GetBestFootballBettingOffersWidget() },
{ "TopFootballBettingOffer", Client.GetFootballBettingOfferWidget() },
{ "BestFootballFreeBetOffers", Client.GetBestFootballSignUpOffersWidget() },
{ "TopFootballFreeBetOffer", Client.GetTopFootballSignUpOfferWidget() },
{ "TopHorseRacingFreeBetOffer", Client.GetTopHorseRacingSignUpOfferWidget() },
{ "TopHorseRacingBettingOffer", Client.GetTopHorseRacingBettingOfferWidget() }
};
我有一个 View 组件调用函数,它根据“promotionType”将“vm”应用于字典中的函数:
public IViewComponentResult Invoke(string promotionType, CompanyEnum? companyId)
{
Promotion vm;
if(promotionType == "TopFreeBetOffer")
{
vm = Client.GetTopBookmakerSpecificSignUpOfferWidget((CompanyEnum)companyId);
}
else if (promotionType == "BestFreeBetOffers")
{
vm = Client.GetBestBookmakerSpecificSignUpOffersWidget((CompanyEnum)companyId);
}
else if (promotionType == "TopBettingOffer")
{
vm = Client.GetTopBookmakerSpecificBettingOfferWidget((CompanyEnum)companyId);
}
else if (promotionType == "BestBettingOffers")
{
vm = Client.GetBestBookmakerSpecificBettingOffersWidget((CompanyEnum)companyId);
}
else
{
vm = availablePromotions[promotionType];
}
return View(vm);
}
如您所见,我有一些函数采用名为“companyId”的参数。
如何才能将带有参数的函数添加到我的字典中,而不是使用 if 语句?
最佳答案
您可以将委托(delegate)存储在字典中,对于不需要参数的方法,您可以忽略它。通过这种方式,您可以将它们全部存储在其中:
private Dictionary<string, Func<CompanyEnum?, Promotion>> availablePromotions = new Dictionary<string, Func<CompanyEnum?, Promotion>>()
{
{ "BestHorseRacingFreeBetSidebarOffers", companyId => Client.GetHorseRacingSignUpOffersSidebarWidget() },
{ "BestHorseRacingBettingSidebarOffers", companyId => Client.GetHorseRacingBettingOffersSidebarWidget() },
{ "TopFreeBetOffer", companyId => Client.GetTopBookmakerSpecificSignUpOfferWidget(companyId) },
{ "BestFreeBetOffers", companyId => Client.GetBestBookmakerSpecificSignUpOffersWidget(companyId) },
// ...
};
你的Invoke
方法会变得简洁(也许使用TryGetValue
):
public IViewComponentResult Invoke(string promotionType, CompanyEnum? companyId)
{
Promotion vm = availablePromotions[promotionType](companyId);
return View(vm);
}
关于c# - 包含函数和可选参数的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57893191/