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