如何提取重构属性

时间:2010-04-27 14:03:27

标签: c#

我有这个属性

public List<PointK> LineList
{get;set;}

PointK由以下结构组成:

string Mark{get;set;}
double X{get;set;}
doible Y{get;set;}

现在,我有以下代码:

   private static Dictionary<string , double > GetY(List<PointK> points)
    {
        var invertedDictResult = new Dictionary<string, double>();
        foreach (var point in points)
        {
            if (!invertedDictResult.ContainsKey(point.Mark))
            {
                invertedDictResult.Add(point .Mark, Math.Round(point.Y, 4));
            }

        }

        return invertedDictResult;
    }


   private static Dictionary<string , double > GetX(List<PointK> points)
    {
        var invertedDictResult = new Dictionary<string, double>();
        foreach (var point in points)
        {
            if (!invertedDictResult.ContainsKey(point.Mark))
            {
                invertedDictResult.Add(point .Mark, Math.Round(point.X, 4));
            }

        }

        return invertedDictResult;
    }

如何重组上述代码?

1 个答案:

答案 0 :(得分:2)

您可以使用

 private static Dictionary<string , double > GetCoordinate
                    (List<PointK> points, Func<Point, double> selector) 

    { 
        var invertedDictResult = new Dictionary<string, double>(); 
        foreach (var point in points) 
        { 
            if (!invertedDictResult.ContainsKey(point.Mark)) 
            { 
                invertedDictResult.Add(point.Mark, Math.Round(selector(point), 4)); 
            } 

        } 

        return invertedDictResult; 
    } 

并将您的方法缩小为

 private static Dictionary<string , double > GetX(List<PointK> points) 
    {         
        return GetCoordinate(points, p => p.X); 
    }