[英]Generic Method Constraint of child class issue
First here's the break down of the class hierarchy:首先是类层次结构的分解:
public class Entity {
}
public abstract class AuditBase<T> {
protected abstract void SomeMethod();
}
public class EntityAudit : AuditBase<Entity> {
protected override void SomeMethod() {
}
}
Then, I have a method with a constraint like so:然后,我有一个具有如下约束的方法:
public async Task<IEnumerable<T>> Query<T>(int id) where T : AuditBase<T>
{
var instance = Activator.CreateInstance<T>();
var refTable = instance.RefTable;
var collection = _context.Database.GetCollection<T>("Audit");
var filter = String.Join("{ RefTable: '", refTable, "', Object: { Id: {'$eq': ", id.ToString(), "} } }");
return await collection.FindSync<T>(filter).ToListAsync();
}
However, I get an error when I use the following code:但是,当我使用以下代码时出现错误:
var result = await Query<EntityAudit>(5);
The error is:错误是:
The type 'EntityAudit' cannot be used as type parameter 'T' in the generic type of method 'Audit.Query<T>(int)'. There is no implicit reference conversion from 'EntityAudit' to 'AuditBase<EntityAudit>'.
I kind of understand the issue.我有点理解这个问题。 My goal is really to restrict the returned
IEnumerable
to only contain objects that are children of AuditBase
.我的目标是将返回的
IEnumerable
限制为仅包含AuditBase
子对象。 Currently, it's trying to return items of type 'Entity' due to T
.目前,由于
T
,它正在尝试返回“实体”类型的项目。
I can't do the constraint as so: ... where T: Audit
as Audit
"requires one parameter."我不能这样做约束:
... where T: Audit
as Audit
“需要一个参数”。
Any thoughts?有什么想法吗? How do I implement the constraint?
如何实现约束?
So I ended up doing the following:所以我最终做了以下事情:
public async Task<IEnumerable<T>> Query<T,U>(int id) where T: AuditBase<U>
{
...
}
var result = await Query<EntityAudit, Entity>(5)
This works.这有效。
But, is there a better way?但是,有没有更好的方法?
create a non generic audit base base class创建一个非通用审计基类
//...
public abstract class AuditBase {
//...
}
public abstract class AuditBase<T> : AuditBase {
protected abstract void SomeMethod();
}
//...
and use that for the constraint并将其用于约束
public async Task<IEnumerable<T>> Query<T>(int id) where T : AuditBase {
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.