考虑以下两种方法,它们本质上是相互复制和粘贴的版本
public static List<Book> GetSubSet(List<Book> incomingList)
{
List<Book> returnList = new List<Book>();
Random r = new Random();
Console.WriteLine("Enter size of random subset: ");
int randomInt = 0;
int size = Convert.ToInt32(Console.ReadLine());
while (size > incomingList.Count)
{
Console.WriteLine("Size too large, enter smaller subset: ");
size = Convert.ToInt32(Console.ReadLine());
}
while (returnList.Count < size)
{
randomInt = r.Next(incomingList.Count);
if (!returnList.Contains(incomingList[randomInt]))
{
returnList.Add(incomingList[randomInt]);
}
}
return returnList;
}
public static List<Pet> GetSubSet(List<Pet> incomingList)
{
Random r = new Random();
List<Pet> returnList = new List<Pet>();
Console.WriteLine("Enter random subset size: ");
int size = Convert.ToInt32(Console.ReadLine());
while (size > incomingList.Count)
{
Console.WriteLine("Size too large. Enter random subset size: ");
size = Convert.ToInt32(Console.ReadLine());
}
while (returnList.Count < size)
{
int randomInt = r.Next(incomingList.Count);
if (!returnList.Contains(incomingList[randomInt]))
{
returnList.Add(incomingList[randomInt]);
}
}
return returnList;
}
显然这不是很面向对象,我希望有一个可以处理任何类型的单一方法。我不想使用继承,因为书和狗之间没有逻辑联系,我不希望包含类型,因为包含也没有意义。所以我们留下了一个界面。就像是
interface ISubset
{
IEnumerable<T> GetSubset();
}
我见过,但我不知道如何使尖括号接受任何通用类型。如何使 IEnumerable 类型成为通用类型,以便可以在任何类上实现 GetSubset 方法?