Convert to Method Group Resharper

左心房为你撑大大i 提交于 2019-12-04 02:44:41

问题


I have written a method below like this:

internal static IList<EmpowerTaxView> GetEmpowerTaxViewsByLongAgencyAndAgencyTaxTypes(
   IList<EmpowerCompanyTaxData> validEmpowerCompanyTaxDatas,
   IList<EmpowerTaxView> empowerTaxViews)
{
    IList<EmpowerTaxView> result = new List<EmpowerTaxView>();

    foreach (EmpowerCompanyTaxData empowerCompanyTaxData in validEmpowerCompanyTaxDatas)
    {
         IList<EmpowerTaxView> validEmpowerTaxViews =
           GetEmpowerTaxViewsByLongAgencyAndTaxType(
             empowerCompanyTaxData, empowerTaxViews);

         validEmpowerTaxViews.ToList().ForEach(delegate(EmpowerTaxView etv)
         {
              result.Add(etv);   
         });   
    }

    return result;
}

And for this method, the resharper says:

validEmpowerTaxViews.ToList().ForEach(delegate(EmpowerTaxView etv)
{
    result.Add(etv);   
});

Convert to Method Group. What does this mean and what should be done to get rid of this.


回答1:


JaredPar already provided the correct answer, I just wanted to suggest a simpler implementation of the method:

internal static IList<EmpowerTaxView> GetEmpowerTaxViewsByLongAgencyAndAgencyTaxTypes(
    IList<EmpowerCompanyTaxData> validEmpowerCompanyTaxDatas,
    IList<EmpowerTaxView> empowerTaxViews)
{
    var results =
        from empowerCompanyTaxData in validEmpowerCompanyTaxDatas
        from etv in GetEmpowerTaxViewsByLongAgencyAndTaxType(
            empowerCompanyTaxData, empowerTaxViews)
        select etv;
    return results.ToList();
}



回答2:


What Resharper means is that you can express the ForEach code more simply by using the method group Add. Example:

validEmpowerTaxViews.ToList().Foreach(result.Add);

The method group defined by Add is compatible with the delegate expected by ForEach and hence the C# compiler will take care of doing the conversion. The default in Resharper is to prefer method groups over lambdas and explicit delegate creation statements.




回答3:


Accept Resharper's suggestion to see what changes it makes. You can always undo them.

If you aren't happy with the change and don't want Resharper suggesting it in future then you can disable that specific option - the others will remain available. See the answer here for details.

Resharper: vars



来源:https://stackoverflow.com/questions/6988730/convert-to-method-group-resharper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!