【发布时间】:2018-01-23 22:14:06
【问题描述】:
我正在尝试创建一个接口和一个具体实现,其中接口是泛型类型并且其中一个方法具有泛型参数。
我想保留 GetPagedList 方法参数,resourceParams,通用,以便我可以为接口的不同实现传递不同的 resourceParams 对象。
当使用下面显示的代码时,我得到了错误;
方法“ShippingServicesRepository.GetPagedList(U)”的类型参数“U”的约束必须匹配接口方法 IBaseRepository.GetPagedList(U) 的类型参数“U”的约束。考虑改用显式接口实现
这是我的界面;
public interface IBaseRepository<T>
{
bool Save();
bool Exists(int recordId);
bool MarkForDeletion(int recordId);
PagedList<T> GetPagedList<U>(U resourceParams) where U : class;
T Get(int id);
void Add(T record);
void Update(T record);
}
这是我的实现;
public class ShippingServicesRepository<T> : IBaseRepository<T>
{
// /--- GetPagedList is what is throwing the error
// |
public PagedList<T> GetPagedList<U> (U resourceParams) where U : ShippingServicesResourceParameters
{
try
{
var collectionBeforePaging =
_manifestContext.ShippingServices
.ApplySort(resourceParams.OrderBy, _propertyMappingService.GetPropertyMapping<ShippingServicesDto, ShippingServices>());
if (!string.IsNullOrEmpty(resourceParams.SearchQuery))
{
var searchQueryForWhereClause = resourceParams.SearchQuery.Trim().ToLowerInvariant();
collectionBeforePaging = collectionBeforePaging
.Where(a => a.ReferenceId.ToLowerInvariant().Contains(searchQueryForWhereClause));
}
collectionBeforePaging = collectionBeforePaging
.Where(d => d.DeleteFlag == resourceParams.DeleteFlag);
return (dynamic)PagedList<ShippingServices>.Create(collectionBeforePaging,
resourceParams.PageNumber,
resourceParams.PageSize);
}
catch (Exception)
{
_logger.LogError(500, "ShippingServices Filter [{FILTER}]", resourceParams);
throw;
}
}
public void Add(T record)
{
...
}
public bool Exists(int recordId)
{
...
}
public T Get(int id)
{
...
}
public bool MarkForDeletion(int recordId)
{
...
}
public bool Save()
{
...
}
public void Update(T record)
{
...
}
}
这是我的 ShippingServicesResourceParameters 类
public class ShippingServicesResourceParameters : BaseResourceParameters
{
public string FileName { get; set; }
}
这里是 ShippingServicesResourceParameters 继承的 BaseResourceParameters 类
public class BaseResourceParameters
{
private int _pageSize;
public int PageNumber { get; set; } = 1;
public int PageSize
{
get
{
return _pageSize;
}
set
{
_pageSize = (value > MaxPageSize) ? MaxPageSize : value;
if (value == 0)
{
_pageSize = 10; // set a default size
}
}
}
public int MaxPageSize { get; set; } = 20;
public bool DeleteFlag { get; set; }
public string SearchQuery { get; set; }
public string OrderBy { get; set; } = "Id";
public string Fields { get; set; }
}
如果我没有在具体实现中的方法签名和接口中的“where U:class”中添加“where U: ShippingServicesResourceParameters”,我得到一个“无法从方法组转换为字符串...”在具体实现中第一次使用 resourceParams 变量时出错。 (在“.ApplySort(resourceParams.OrderBy”)
我在这里错过了什么?
【问题讨论】:
-
在方法中使用具体类时所有泛型的任何原因?
-
@MikePerrenoud 你不能用另一个类约束来指定类。
-
请制作一个大约是该复制品大小的二十分之一的复制品。这里有大量完全不相关的垃圾。
-
错误信息告诉你问题到底出在哪里。您正在编写的方法有哪些限制?您希望它实现的接口实现的约束是什么?他们是一样的吗? (提示,它们不是,错误消息告诉你的也是。)
-
不要随意更改约束条件,希望它们能解决问题。这不是一个可靠的工程方法。 首先了解问题,然后然后解决它。
标签: c# generics interface .net-core asp.net-core-mvc-2.0