什么是避免重复此代码的最佳方法

leo*_*ora 4 c# refactoring

我有以下方法:

    public  int CountProperty1
    {
        get
        {
            int count = 0;
            foreach (var row in Data)
            {
                count = count + row.Property1;
            }
            return count ;
        }
    }

    public  int CountProperty2
    {
        get
        {
            int count = 0;
            foreach (var row in Data)
            {
                count = count + row.Property2;
            }
            return count ;
        }
    }
Run Code Online (Sandbox Code Playgroud)

什么是避免重复的最佳方法,并尽可能多地共享代码

dri*_*iis 10

如何使用LINQ和Sum扩展方法?

public int CountProperty1 
{
    get { return Data.Sum(r => r.Property1); }
} 
Run Code Online (Sandbox Code Playgroud)

如果不是一个选项,您可以将逻辑重构为您自己的sum方法:

public  int CountProperty1
{
    get
    {
        return CountProperty(r => r.Property1);
    }
}

public  int CountProperty2
{
    get
    {
        return CountProperty(r => r.Property2);
    }
}

private int CountProperty(Func<Row,int> countSelector)
{
     int count = 0;
     foreach (var row in Data)
     {
         count = count + countSelector(row);
     }
     return count ;
}
Run Code Online (Sandbox Code Playgroud)

关于最后一个例子的注意事项:我编写了"行"类型,因为从你的例子中看不出来.用适当的类型替换.