[英]return a list of generic C#
我有一个 singleton class,包含几个数据列表。 我想要一个 function 根据请求的数据类型返回列表之一
public class Book
{
public string Name { get; set; }
public int Pages { get; set; }
}
public class DVD
{
public string Name { get; set; }
public TimeSpan Length { get; set; }
}
public class DBReferenceSingleton
{
private List<Book> _bookList;
private List<DVD> _dvdList;
public IEnumerable<Entity> GetEntities<Entity>() where Entity : class
{
switch(typeof(Entity).Name)
{
case nameof(Book):
return _bookList;
case nameof(DVD):
return _dvdList;
}
return null;
}
这不起作用,因为需要转换。 我想知道是否有任何优雅的解决方案(不序列化所有元素或实现 IConvertible)?
看起来 generics 似乎不是这里的正确工具; 尤其是因为Book
和DVD
没有共同的基础 class。
我认为你应该有两种方法:
public List<Book> GetBooks() => _bookList;
public List<DVD> GetDvds() => _dvdList;
你试过做演员吗?
public class Book
{
public string Name { get; set; }
public int Pages { get; set; }
}
public class DVD
{
public string Name { get; set; }
public TimeSpan Length { get; set; }
}
public class DBReferenceSingleton
{
private List<Book> _bookList;
private List<DVD> _dvdList;
public IEnumerable<Entity> GetEntities<Entity>() where Entity : class
{
switch(typeof(Entity).Name)
{
case nameof(Book):
return _bookList as List<Entity>;
case nameof(DVD):
return _dvdList as List<Entity>;
}
return null;
}
}
如果 object 类型错误,“as List< Entity >”将返回 null,如果类型正确,则返回 object 作为类型。 A = B as C 模式也适用于继承类型,只要记住检查 null 返回的值,以防您的类型不像在这种情况下那样广为人知
关于在这种情况下使用泛型方法的有用性的旁注:在这种方法中,您每次都被迫显式设置实体的类型,这意味着您的方法在功能上是非泛型的 - 所以您不妨明确两个方法。
像您所拥有的通用方法可能更有用的一种情况是,如果 book 和 dvd 都从基础 class 继承,并且您有一些后续方法需要从列表中操作。 例如,您可能最终想要在代码中执行类似的操作:
public class Book : Rentable
{
public int Pages { get; set; }
}
public class DVD : Rentable
{
public TimeSpan Length { get; set; }
}
public class Rentable
{
public string Name { get; set; }
public string borrowedBy { get; set; }
}
public class DBReferenceSingleton
{
private List<Book> _bookList;
private List<DVD> _dvdList;
public enum RentableType { Book, DVD }
public IEnumerable<Rentable> GetEntities(RentableType entityType)
{
switch (entityType)
{
case RentableType.Book:
return _bookList.ToList<Rentable>();
case RentableType.DVD:
return _dvdList.ToList<Rentable>();
default:
throw new NotImplementedException($"Entity {entityType} not supported");
}
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.