C# IQueryable上的通用扩展方法<;T>;
我已经在IQueryable上编写了一个扩展方法,它返回相同类型的IQueryable,只是过滤了一点。 假设是这样的:C# IQueryable上的通用扩展方法<;T>;,c#,generics,extension-methods,C#,Generics,Extension Methods,我已经在IQueryable上编写了一个扩展方法,它返回相同类型的IQueryable,只是过滤了一点。 假设是这样的: public static IEnumerable<T> Foo<T>(this IEnumerable<T> source, int? howmany = null) { if (howmany.HasValue) return source.Take(howmany.Value); return sour
public static IEnumerable<T> Foo<T>(this IEnumerable<T> source, int? howmany = null)
{
if (howmany.HasValue)
return source.Take(howmany.Value);
return source;
}
现在,鉴于strLinqResult
是IQueryable
,我需要将其称为strLinqResult.Bar()代码>
关键是我必须通过这两种类型,即使第一种类型已经为人所知,因为我在已经定义的IQuerable
上调用该方法
由于调用Foo(2)
和而不是Foo(2)
就足够了,我认为编译器能够自动“传递/猜测”类型
那么为什么我需要调用第二个方法Bar()代码>而不仅仅是Bar()
实际代码:
public static ListResponse<TResponse>
BuildListResponse<T,TResponse>(this IQueryable<T> iq, ListRequest request)
where TResponse: new()
{
var result = iq.ApplyListRequestParams(request).ToList().ConvertAll(x => x.TranslateTo<TResponse>());
var tcount = iq.Count();
return new ListResponse<TResponse> {
Items = result,
_TotalCount = tcount,
_PageNumber = request._PageNumber ?? 1,
};
}
公共静态列表响应
BuildListResponse(此IQueryable iq、ListRequest请求)
where响应:new()
{
var result=iq.ApplyListRequestParams(request.ToList().ConvertAll(x=>x.TranslateTo());
var tcount=iq.Count();
返回新的ListResponse{
项目=结果,
_TotalCount=t计数,
_页码=请求。\u页码??1,
};
}
ApplyListRequestParams
是示例代码中的一种Foo
方法-它只应用ListRequest
对象中可用的分页和排序参数
项目
是类列表响应中的公共列表项目
TranslateTo
是ServiceStack中的一种方法
在NHibernate(T是域模型)返回的IQueryable
上调用的上述方法获取请求参数(排序、分页),应用它们,然后将结果列表从DomainModel
转换为类型为treponse
的对象。然后将列表包装在一个通用响应类中(generic,因此它对于许多DTO类型都是可重用的)如果我正确理解了您的问题,那么您将尝试输入尽可能少的参数。那是不可能的。不管是全有还是全没有,它都可以自己解决
只指定一些的问题在于,您将能够使用少1个类型参数引入类似的方法,并且现在已经破坏了实现
但你有没有可能也分享你原来的问题?也许可以让编译器以其他方式解决问题?您是否尝试过将定义切换到Bar(…)
?@PinnyM是的,我尝试过。它仍然说我需要通过2类考试parameters@Jon我可能误解了另一种解决方案,但是扩展实际的类是不可能的——它需要是扩展方法@migajek:链接的答案建议在一个单独的泛型类(不是您正在使用的类)上使用静态方法。或者,您可以安排使用中间类型的扩展方法语法进行调用,但这需要两个扩展方法调用。仅对一个调用使用扩展方法语法要求编译器仅推断其中一个类型参数,但事实并非如此。假设您添加了条(此IEnumerable源代码)
。如果编译器接受您的速记,那么现在就可以明确strLinqResult.Bar()代码>指的是Bar
或Bar
。我想这就是约翰尼·斯科夫达尔在回答中的意思,但我想说清楚。
public static ListResponse<TResponse>
BuildListResponse<T,TResponse>(this IQueryable<T> iq, ListRequest request)
where TResponse: new()
{
var result = iq.ApplyListRequestParams(request).ToList().ConvertAll(x => x.TranslateTo<TResponse>());
var tcount = iq.Count();
return new ListResponse<TResponse> {
Items = result,
_TotalCount = tcount,
_PageNumber = request._PageNumber ?? 1,
};
}