我喜欢将我的定义与我的实现分开。我有一个接口实体:限制泛型在特定情况下失败
public interface Entity<E> where E : Entity<E>
{
EntityId EntityId { get; }
bool ReadOnly { get; }
void FailIfReadOnly();
E Copy();
}
E是实际的实体类型,如Customer:
public interface Customer : Entity<Customer>
{
}
我的问题是FailIfReadOnly(执行):如果只读== true,则抛出一个EntityIsReadOnlyException。
public class EntityIsReadOnlyException<E> where E : Entity<E>
{
public EntityIsReadOnlyException(E entity)
: base(string.Format("Entity {0} is read only", entity.EntityId))
{
}
}
public class EntityImpl<E> : Entity<E> where E : Entity<E>
{
public EntityImpl(E other)
{
}
public bool ReadOnly
{
get;
protected set;
}
public void FailIfReadOnly()
{
if (! ReadOnly) throw new EntityIsReadOnlyException<E>(this);
}
}
的throw new EntityIsReadOnlyException<E>(this);
导致编译错误:
The best overloaded method match for 'EntityIsReadOnlyException.EntityIsReadOnlyException(E)' has some invalid arguments
Argument '1': cannot convert from 'EntityImpl' to 'E'
我可以这样做:
EntityIsReadOnlyExcetion<Customer> exc = new EntityIsReadOnlyException<Customer>(customerImpl);
,甚至:
Entity<E> entity = new EntityImpl<E>(this);
但不是:
EntityIsReadOnlyException<E> exc = new EntityIsReadOnlyException<E>(this);
在这两种情况下,E仅限于实体的子类。我的问题是,为什么我得到这个编译错误?这可能很简单。
接口上“where E:Entity”的用途是什么? –
2009-12-06 21:48:57
这是一个递归定义是不是? IE类型限制是一个实体>? 这甚至可能吗? –
Spence
2009-12-06 21:57:20
@marcgravell - 通常这种递归类型限制的目的是在基类中实现可以返回派生类型的克隆或副本。 – x0n 2009-12-06 22:05:35