通用方法约束?

时间:2013-01-09 21:21:54

标签: c# generics

我有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;
}

如您所见,该方法做同样的事情。因此我不想创建这两次。我觉得这是可能的,但我正在考虑错误。我对generics还不是很熟悉。谢谢。

1 个答案:

答案 0 :(得分: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#文化的开发人员来说,似乎都是合理且可读的。当然,它可以为您提供几行代码。请记住,您编写的代码越多,出错的可能性就越高。

相关问题