2013-01-09 77 views
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; 
} 

正如您所看到的,该方法执行相同的操作。所以我不想这样做两次。我觉得这是可能的,但我错误地思考它。我还没有完全体验泛型。谢谢。

+1

'FirstGridList'和'SecondGridList'是否共享相同的基类? –

回答

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#文化任何开发。当然,它可以帮你省去几行代码。请记住,你写的代码越多,出错的概率就越高。

+3

在这一点上,你甚至可以摆脱通用的'',只需将它直接输入到'IGridList'。 –

+0

哦,是的,克里斯,你完全正确。我已经更新了我的回答,以包含您的评论。感谢您指出了这一点。 –

+0

@ChrisSinclair是否因为T只在方法内部使用,并且具有接口约束?我们可以概括并说出何时使用类或接口约束,如果它用作Input,则不需要使用Generic类型? – MBen