【发布时间】:2013-05-10 09:55:48
【问题描述】:
我有一个包含此成员的接口(由存储库使用):
T FindById<T, TId>(TId id)
where T : class, IEntity<TId>
where TId : IEquatable<TId>;
这允许调用者指定实体类型 (T) 及其类型为 Id 字段 (TId)。然后,该接口的实现者会找到 T 类型的实体,并使用 id 参数根据它们的 id(在 IEntity<TId> 上定义)过滤它们。
目前我这样称呼它:
int id = 123;
var myApproval = PartsDC.FindById<Approval, int>(id);
理想情况下我想这样做:
int id = 123;
var myApproval = PartsDC.FindById<Approval>(id);
我已经阅读了这个问题的答案:
Partial generic type inference possible in C#?
我知道我无法获得我想要的语法,但可以接近。由于我的通用参数限制,我无法完全正确地设置它。
这是我目前所拥有的:
public class FindIdWrapper<T> where T : class
{
public readonly IDataContext InvokeOn;
public FindIdWrapper(IDataContext invokeOn)
{
InvokeOn = invokeOn;
}
T ById<TId>(TId id) where TId : IEquatable<TId>
{
return InvokeOn.FindById<T, TId>(id);
}
}
public static class DataContextExtensions
{
public static FindIdWrapper<T> Find<T>(this IDataContext dataContext) where T : class, IEntity
{
return new FindIdWrapper<T>(dataContext);
}
}
我得到的编译错误是:
The type 'T' cannot be used as type parameter 'T' in the generic type or method 'PartsLegislation.Repository.IDataContext.FindById<T,TId>(TId)'. There is no implicit reference conversion from 'T' to 'PartsLegislation.Repository.IEntity<TId>'.
我明白它在说什么,因为我的包装类中的 T 仅被限制为引用类型,但 FindById 函数希望它是 IEntity<TId>,但我不能这样做,因为 @ 987654336@ 在方法中(否则我会回到第一方)。
我怎样才能解决这个问题(或者我不能)?
【问题讨论】:
-
您不能将
TID作为约束添加到FindIdWrapper吗? -
@Nick 不,因为
TID在部分应用时是未知的
标签: c# generics type-inference