0

我有 2 个类,其中包含将填充单独网格的数据。网格非常相似,但差异足以需要使用 2 个类。两个网格都包含一个名为“GetDuplicates”的函数,在我实现这些类的地方,我有一个方法来检查该类是否有重复项并返回一条消息来表明这一点。

private bool HasDuplicates(FirstGridList firstList)
{
    var duplicates = firstList.FindDuplicates();
    if (duplicates.Count > 0)
    {
        // Do Something
        return true;
    }
    return false;
}

我希望能够同时使用 FirstGridList 和 SecondGridList 调用该方法。我只是不知道如何正确实现泛型约束,然后将泛型输入参数转换为正确的类型。如同:

private bool HasDuplicates<T>(T gridList)
{
    // Somehow cast the gridList to the specific type
    // either FirstGridList or SecondGridList

    // Both FirstGridList and SecondGridList have a method FindDuplicates
    // that both return a List<string>
    var duplicates = gridList.FindDuplicates();
    if (duplicates.Count > 0)
    {
        // Do Something
        return true;
    }
    return false;
}

如您所见,该方法执行相同的操作。因此我不想创建两次。我觉得这是可能的,但我想错了。我对泛型还没有完全的经验。谢谢你。

4

1 回答 1

7

您可以让两个网格都实现一个通用接口,例如:

public interface IGridList
{
    public IList<string> FindDuplicates();
}

然后基于此接口定义您的通用约束:

private bool HasDuplicates<T>(T gridList) where T: IGridList
{
    // Both FirstGridList and SecondGridList have a method FindDuplicates
    // that both return a List<string>
    var duplicates = gridList.FindDuplicates();
    if (duplicates.Count > 0)
    {
        // Do Something
        return true;
    }
    return false;
}

显然你FirstGridListSecondGridList应该实现IGridList接口和FindDuplicates方法。

或者你甚至可以在这个阶段摆脱泛型:

private bool HasDuplicates(IGridList gridList)
{
    // Both FirstGridList and SecondGridList have a method FindDuplicates
    // that both return a List<string>
    var duplicates = gridList.FindDuplicates();
    if (duplicates.Count > 0)
    {
        // Do Something
        return true;
    }
    return false;
}

顺便说一句,在这个阶段您甚至可以摆脱该HasDuplicates方法,因为它不会为您的应用程序带来太多价值。我的意思是面向对象编程早在泛型或 LINQ 之类的东西之前就存在了,所以为什么不使用它:

IGridList gridList = ... get whatever implementation you like
bool hasDuplicates = gridList.FindDuplicates().Count > 0;

对于任何具有基本 C# 文化的开发人员来说,这似乎是合理且可读的。当然,它可以为您节省几行代码。请记住,您编写的代码越多,出错的可能性就越高。

于 2013-01-09T21:25:38.063 回答