我编写了这个接口
public interface IRepository
{
IEnumerable<T> GetAll<T>();
}我有这门课
public class Customer
{
public int Id { get; set; }
public string CNPJ { get; set; }
public string Name { get; set; }
public string BusinessArea { get; set; }
}和
public class CustomerRepository : IRepository
{
public IEnumerable<T> GetAll<T>()
{
foreach (var line in this.data)
{
string[] CustomerData = Regex.Split(line, @"\s+(?=002#)");
foreach (var CustomerItem in CustomerData)
{
string[] d = Regex.Split(CustomerItem, "#");
yield return new Customer() { BusinessArea = d[3], CNPJ = d[1], Name = d[2] };
}
}
}
}我想使用GetAll加载其他类,但是编译器显示此错误“不能隐式地将'Prova.Domain.Customer‘类型转换为'T'”。
我试过用(T)做演员,但我解决不了这个问题。我如何解决这个通用的强制转换?
谢谢
发布于 2020-01-15 15:51:55
您的存储库应该是通用的,而不仅仅是方法:
public interface IRepository<T>
{
IEnumerable<T> GetAll();
}
public class CustomerRepository : IRepository<Customer>
{
public IEnumerable<Customer> GetAll()
{
foreach (var line in this.data)
{
string[] CustomerData = Regex.Split(line, @"\s+(?=002#)");
foreach (var CustomerItem in CustomerData)
{
string[] d = Regex.Split(CustomerItem, "#");
yield return new Customer() { BusinessArea = d[3], CNPJ = d[1], Name = d[2] };
}
}
}
}由于您的CustomerRepository为Customer对象提供了特定的实现,因此该方法本身不能像您正在观察的那样保持泛型。
发布于 2020-01-15 15:51:38
IRepository应该是泛型的(IRepository<T>),CustomerRepository应该实现IRepository<Customer>
public class CustomerRepository : IRepository<Custom>然后,您将创建另一个实现IRepository<Other>并返回Other对象的存储库。
泛型是关于编译时安全的。这不是从一种类型到另一种类型的“转换”。
发布于 2020-01-15 15:51:48
在接口中指定泛型:
public interface IRepository<T> where T : class在你们班也是一样:
public class CustomerRepository<T> : IRepository<T> where T : classhttps://stackoverflow.com/questions/59754913
复制相似问题