我有两个小班,Pet
和Book
,每个都有几个属性,而且函数的方法类似于
public static List<T> GetSubSet<T>(List<T> incomingList)
{
var returnList = new List<T>();
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;
}
获取对象的通用列表并返回较小的子集。该功能有效,可以使用Pet或Book对象。我想在包含两者 Pet和Book类型的列表中使用相同的函数。我知道如何做到这一点的最好方法是使用接口(继承在这里没有意义)。
interface ISubset<T>
{
IEnumerable<T> GetSubset();
}
当我在Pet类上实现接口时,它看起来像
class Pet : ISubset<Pet>
在我的主课程中,我有一份宠物和书籍清单。我想将这两个对象添加到ISubset
对象列表中,这样我就可以在两者上使用GetSubset函数了。但是,我不能声明像
List<ISubset<T>> list = new List<ISubset<T>>();
我收到错误'the type or namespace T could not be found
当接口接受泛型类型时,如何声明ISubset对象列表?
好的,我有两个列表,比如
List<Pet> petList = new List<Pet>();
petList.Add(new Pet() { Name = "Mr.", Species = "Dog" });
petList.Add(new Pet() { Name = "Mrs.", Species = "Cat" });
petList.Add(new Pet() { Name = "Mayor", Species = "Sloth" });
petList.Add(new Pet() { Name = "Junior", Species = "Rabbit" });
List<Book> bookList = new List<Book>();
bookList.Add(new Book() { Author = "Me", PageCount = 100, Title = "MyBook" });
bookList.Add(new Book() { Author = "You", PageCount = 200, Title = "YourBook" });
bookList.Add(new Book() { Author = "Pat", PageCount = 300, Title = "PatsBook" });
如果我想将这些列表一起添加到另一个列表中,该类型应该是什么?
答案 0 :(得分:4)
您只能使用List<object>
,但如果您想按照建议的方式进行操作,那么您需要创建一个带有覆盖两个类的签名的界面
public interface IGen
{
int A;
int Method;
}
然后在类
中继承/实现此接口public class Pet : IGen
{
public int A { get; set; }
private int Method(){ ... }
}
public class Book : IGen
{
public int A { get; set; }
private int Method(){ ... }
}
然后你可以传入你的GetSubSet
喜欢
GetSubSet<IGen>(List<IGen> incomingList) { ... }
我希望这会有所帮助。
答案 1 :(得分:1)
List<object>
应该可以正常使用。
以下是在LinqPad中测试的
void Main()
{
List<Pet> petList = new List<Pet>();
petList.Add(new Pet() { Name = "Mr.", Species = "Dog" });
petList.Add(new Pet() { Name = "Mrs.", Species = "Cat" });
petList.Add(new Pet() { Name = "Mayor", Species = "Sloth" });
petList.Add(new Pet() { Name = "Junior", Species = "Rabbit" });
List<Book> bookList = new List<Book>();
bookList.Add(new Book() { Author = "Me", PageCount = 100, Title = "MyBook" });
bookList.Add(new Book() { Author = "You", PageCount = 200, Title = "YourBook" });
bookList.Add(new Book() { Author = "Pat", PageCount = 300, Title = "PatsBook" });
List<object> both = petList.OfType<object>().Union(bookList.OfType<object>()).ToList().Dump();
}
// Define other methods and classes here
public class Pet
{
public string Name { get; set; }
public string Species { get; set; }
}
public class Book
{
public string Author { get; set; }
public int PageCount { get; set; }
public string Title { get; set; }
}