如何将多个属性作为参数传递,然后正确使用它们?

时间:2014-05-27 12:42:14

标签: c# generics

我得到了这种通用方法;

public CompareResult<T> GenericCompare<T>(CompareLogic compareLogic, List<T> OldObject, List<T> NewObject, Func<T, int> DelProperty)
{
    var result = new CompareResult<T>();

    var OldObjectId = OldObject.Select(DelProperty);
    var NewObjectId = NewObject.Select(DelProperty);

    var ObjectAddedId = NewObjectId.Except(OldObjectId);
    var ObjectRemovedId = OldObjectId.Except(NewObjectId);

    var SameOldObject = OldObject.Where(x => !ObjectRemovedId.Contains(DelProperty(x)));
    var SameNewObject = NewObject.Where(x => !ObjectAddedId.Contains(DelProperty(x)));

    var SameObject = SameOldObject.Join(
                                            SameNewObject,
                                            Older => DelProperty(Older),
                                            Newer => DelProperty(Newer),
                                            (Older, Newer) => new { older = Older, newer = Newer }
                                        );

    foreach (var same in SameObject)
    {
        var ObjectCompare = compareLogic.Compare(same.older, same.newer);
        if (!ObjectCompare.AreEqual)
        {
            var Modified = ObjectCompare.Differences.Select(x => x.PropertyName);
            result.ObjectModified.Add(new Tuple<T, T, IEnumerable<string>>(same.older, same.newer, Modified));
        }
    }
    result.ObjectRemoved = OldObject.Where(x => ObjectRemovedId.Contains(DelProperty(x))).ToList();
    result.ObjectAdded = NewObject.Where(x => ObjectAddedId.Contains(DelProperty(x))).ToList();

    return result;
}

对于DelProperty参数,我可以使用这些组合;

  1. 一个字段,int(当前代码)
  2. 两个字段,int,int
  3. 两个字段,字符串,字符串
  4. 参数DelProperty就像是对象的主键,我需要做些什么才能使这段代码与“复合”主键兼容?我有点陷入困境。

    我能想到的唯一一件事是复制/粘贴此代码两次以实现2个缺失的组合,但我担心会有更多的组合,这可能会很容易混乱

1 个答案:

答案 0 :(得分:0)

您可以在密钥类型中添加一个泛型泛型,并使用密钥相等比较器:

public CompareResult<T> GenericCompare<T, K>(CompareLogic compareLogic, List<T> OldObject, List<T> NewObject, Func<T, K> DelProperty, IEqualityComparer<K> keyComparer)
{
    var ObjectAddedId = NewObjectId.Except(OldObjectId, keyComparer);
    var ObjectRemovedId = OldObjectId.Except(NewObjectId, keyComparer);
    ...
}

然后您可以更新当前方法以调用新方法:

public CompareResult<T> GenericCompare<T>(CompareLogic compareLogic, List<T> OldObject, List<T> NewObject, Func<T, int> DelProperty)
{
    return GenericCompare(compareLogic, OldObject, NewObject, DelProperty, EqualityComparer<int>.Default);
}